package org.jeecg.modules.mes.storage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataMateriel;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataReplacematerial;
import org.jeecg.modules.mes.client.InspectClient;
import org.jeecg.modules.mes.client.ProduceClient;
import org.jeecg.modules.mes.client.SystemClient;
import org.jeecg.modules.mes.client.TransactionClient;
import org.jeecg.modules.mes.inspect.entity.MaterielRetreatRecord;
import org.jeecg.modules.mes.order.entity.*;
import org.jeecg.modules.mes.produce.entity.MesCommandbillInfo;
import org.jeecg.modules.mes.produce.entity.MesCommandbillPitem;
import org.jeecg.modules.mes.produce.entity.TurnProduceRecord;
import org.jeecg.modules.mes.storage.entity.*;
import org.jeecg.modules.mes.storage.service.*;
import org.jeecg.modules.mes.storage.utils.AsyncUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 物料凭证抬头
 * @Author: jeecg-boot
 * @Date: 2020-10-15
 * @Version: V1.0
 */
@Api(tags = "物料凭证抬头")
@RestController
@RequestMapping("/storage/mesCertificatePerk")
@Slf4j
public class MesCertificatePerkController extends JeecgController<MesCertificatePerk, IMesCertificatePerkService> {

    @Autowired
    private IMesCertificatePerkService mesCertificatePerkService;

    @Autowired
    private IMesCertificateItemService mesCertificateItemService;

    @Autowired
    private IMesStockManageService mesStockManageService;

    @Autowired
    private IMesStorageWholesaleService mesStorageWholesaleService;

    @Autowired
    private IMesMaterielOccupyService mesMaterielOccupyService;

    @Autowired
    private IMesErrorOperationRecordService iMesErrorOperationRecordService;

    @Autowired
    TransactionClient transactionClient;

    @Autowired
    InspectClient inspectClient;

    @Autowired
    ProduceClient produceClient;

    @Autowired
    SystemClient systemClient;
    @Autowired
    AsyncUtils asyncUtils;

    @Autowired
    private IMesOutproWaterService outproWaterService;



    /*---------------------------------主表处理-begin-------------------------------------*/

    /**
     * 分页列表查询
     *
     * @param mesCertificatePerk
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "物料凭证抬头-分页列表查询")
    @ApiOperation(value = "物料凭证抬头-分页列表查询", notes = "物料凭证抬头-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MesCertificatePerk mesCertificatePerk,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        List<String> likeCode = new ArrayList<>();
        //pda入库根据采购订单号查询
        if(mesCertificatePerk!=null&&StringUtils.isNotBlank(mesCertificatePerk.getQuery6())){
            likeCode = transactionClient.getOrderPurchaseLikeCode(mesCertificatePerk.getQuery6());
        }
        mesCertificatePerk.setQuery6(null);
        QueryWrapper<MesCertificatePerk> queryWrapper = QueryGenerator.initQueryWrapper(mesCertificatePerk, req.getParameterMap());
        if (likeCode!=null&&likeCode.size()>0) {
            queryWrapper.in("purchase_id", likeCode);
        }
        queryWrapper.orderByDesc("create_time");
        Page<MesCertificatePerk> page = new Page<MesCertificatePerk>(pageNo, pageSize);
        IPage<MesCertificatePerk> pageList = mesCertificatePerkService.page(page, queryWrapper);
        for (int i = 0; i < pageList.getRecords().size(); i++) {
            MesCertificatePerk mesCertificatePerk1 = pageList.getRecords().get(i);
            MesOrderPurchase orderPurchaseinfo = transactionClient.getOrderPurchaseById(mesCertificatePerk1.getPurchaseId());
            if (orderPurchaseinfo!=null&&orderPurchaseinfo.getOrderCode()!=null) {
                pageList.getRecords().get(i).setQuery4(orderPurchaseinfo.getOrderCode());
            }
        }
        return Result.ok(pageList);
    }


    @AutoLog(value = "物料凭证抬头-完成质检")
    @ApiOperation(value = "物料凭证抬头-完成质检", notes = "抽检抽测表-完成质检")
    @GetMapping(value = "/commitCheck")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MesCertificatePerk mesCertificatePerk = mesCertificatePerkService.getById(id);
        if (mesCertificatePerk == null) {
            return Result.error("未找到对应数据");
        }
        mesCertificatePerk.setIfFinish("已完成");
        return Result.ok("质检完成");
    }

    /**
     * 添加
     *
     * @param mesCertificatePerk
     * @return
     */
    @AutoLog(value = "物料凭证抬头-添加")
    @ApiOperation(value = "物料凭证抬头-添加", notes = "物料凭证抬头-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MesCertificatePerk mesCertificatePerk) {
        QueryWrapper<MesCertificatePerk> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("purchase_id", mesCertificatePerk.getPurchaseId());
        List<MesCertificatePerk> list = mesCertificatePerkService.list(queryWrapper);
        if (list.size() > 0) {
            return Result.ok(list.get(0));
        }

        String perkCode = systemClient.getdocketcode(null);
        SimpleDateFormat year = new SimpleDateFormat("yyyy");
        String CerYear = year.format(new Date());
        mesCertificatePerk.setCerYear(CerYear);
        mesCertificatePerk.setAffairCode(perkCode);//物料凭证年度
        mesCertificatePerk.setEnrollDate(new Date());
        mesCertificatePerk.setInputTime(new Date());
//    	mesCertificatePerk.setIfFinish("未完成");
//    	mesCertificatePerk.setIfInput("未完成");
        mesCertificatePerkService.save(mesCertificatePerk);
        return Result.ok(mesCertificatePerk);
//        return Result.ok("添加成功！");
    }

    @AutoLog(value = "物料凭证抬头-根据采购订单编号查询")
    @ApiOperation(value = "物料凭证抬头-根据采购订单编号查询", notes = "物料凭证抬头-根据采购订单编号查询")
    @GetMapping(value = "/selectPurchaseId")
    public Result<?> selectPurchaseId(@RequestParam(name = "purchaseId", required = true) String purchaseId) {
        QueryWrapper<MesCertificatePerk> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("purchase_id", purchaseId);
        List<MesCertificatePerk> list = mesCertificatePerkService.list(queryWrapper);
        if (list.size() > 0) {
            return Result.ok(list.get(0));
        }
        return Result.ok(null);
    }


    /**
     * 编辑
     *
     * @param mesCertificatePerk
     * @return
     */
    @AutoLog(value = "物料凭证抬头-编辑")
    @ApiOperation(value = "物料凭证抬头-编辑", notes = "物料凭证抬头-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MesCertificatePerk mesCertificatePerk) {
        mesCertificatePerkService.updateById(mesCertificatePerk);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "物料凭证抬头-通过id删除")
    @ApiOperation(value = "物料凭证抬头-通过id删除", notes = "物料凭证抬头-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        mesCertificatePerkService.delMain(id);
        QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("query3", id);
        mesStorageWholesaleService.remove(queryWrapper);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "物料凭证抬头-批量删除")
    @ApiOperation(value = "物料凭证抬头-批量删除", notes = "物料凭证抬头-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesCertificatePerkService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesCertificatePerk mesCertificatePerk) {
        return super.exportXls(request, mesCertificatePerk, MesCertificatePerk.class, "物料凭证抬头");
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesCertificatePerk.class);
    }
    /*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-物料凭证项目-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    @AutoLog(value = "物料凭证项目-通过主表ID查询")
    @ApiOperation(value = "物料凭证项目-通过主表ID查询", notes = "物料凭证项目-通过主表ID查询")
    @GetMapping(value = "/listMesCertificateItemByMainId")
    public Result<?> listMesCertificateItemByMainId(MesCertificateItem mesCertificateItem,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<MesCertificateItem> queryWrapper = QueryGenerator.initQueryWrapper(mesCertificateItem, req.getParameterMap());
        Page<MesCertificateItem> page = new Page<MesCertificateItem>(pageNo, pageSize);
        IPage<MesCertificateItem> pageList = mesCertificateItemService.page(page, queryWrapper);
        if (pageList.getTotal() == 0) {
            MesCertificatePerk mesCertificatePerk = mesCertificatePerkService.getById(mesCertificateItem.getPerkId());
//			if(mesCertificatePerk.getIfFinish().equals("质检完成")){
//				mesCertificatePerk.setIfInput("入库完成");
//				mesCertificatePerkService.updateById(mesCertificatePerk);
//			}
            String purchaseId = mesCertificatePerk.getPurchaseId();//采购订单id
            MesOrderPurchase purchaseOrder = transactionClient.getOrderPurchaseById(purchaseId);
            String state = purchaseOrder.getIfFinish();
            String receiveState = "收货完成";
            if (StringUtils.isNotBlank(state)) {
                if (state.equals(receiveState)) {
                    mesCertificatePerk.setIfFinish("质检完成");
                    mesCertificatePerkService.updateById(mesCertificatePerk);
                }
            }
        }
        return Result.ok(pageList);
    }

    /**
     * 质检的时候使用
     *
     * @param mesCertificateItem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/checkMesCertificate")
    public Result<?> checkMesCertificate(MesCertificateItem mesCertificateItem,
                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                         HttpServletRequest req) {
        QueryWrapper<MesCertificateItem> queryWrapper = QueryGenerator.initQueryWrapper(mesCertificateItem, req.getParameterMap());
        Page<MesCertificateItem> page = new Page<MesCertificateItem>(pageNo, pageSize);
        IPage<MesCertificateItem> pageList = mesCertificateItemService.page(page, queryWrapper);
        if (pageList.getTotal() == 0) {
            String perkId = mesCertificateItem.getPerkId();
            MesCertificatePerk mesCertificatePerk = mesCertificatePerkService.getById(perkId);
            if (mesCertificatePerk.getIfFinish().equals("未完成")) {
                mesCertificatePerk.setIfFinish("质检完成");
                mesCertificatePerkService.updateById(mesCertificatePerk);
            }
        }
        IPage<MesCertificateItem> pageList1 = mesCertificateItemService.page(page, queryWrapper);
        return Result.ok(pageList1);
    }

    /**
     * 根据打印的标签二维码获取他的item质检信息
     *
     * @param query4
     * @return
     */
    @AutoLog(value = "根据打印的标签二维码获取他的item质检信息")
    @ApiOperation(value = "根据打印的标签二维码获取他的item质检信息", notes = "根据打印的标签二维码获取他的item质检信息")
    @GetMapping(value = "/selectbqByItem")
    public Result<?> selectbqByItem(@RequestParam(name = "query4") String query4) {
        List<MesCertificateItem> mesCertificateItem = mesCertificateItemService.selectbqByItem(query4);
        if (mesCertificateItem.size() == 0) {
            return Result.error("未找到该物料扫描收货信息，请先收货再质检！");
        }
        if ("是".equals(mesCertificateItem.get(0).getIfInspect())) {
            return Result.error("该物料已质检！");
        }
        return Result.OK(mesCertificateItem.get(0));
    }

    @GetMapping(value = "/checkInstruction")
    public Result<?> checkInstruction(MesCertificateItem mesCertificateItem,
                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                      HttpServletRequest req) {
        QueryWrapper<MesCertificateItem> queryWrapper = QueryGenerator.initQueryWrapper(mesCertificateItem, req.getParameterMap());
        Page<MesCertificateItem> page = new Page<MesCertificateItem>(pageNo, pageSize);
        IPage<MesCertificateItem> pageList = mesCertificateItemService.page(page, queryWrapper);
        if (pageList.getTotal() == 0) {
            MesCertificatePerk mesCertificatePerk = mesCertificatePerkService.getById(mesCertificateItem.getPerkId());
            String unFinish = "未完成";
            if (mesCertificatePerk.getIfFinish().equals(unFinish)) {
                mesCertificatePerk.setIfFinish("完成");
                mesCertificatePerkService.updateById(mesCertificatePerk);
            }

        }
        return Result.ok(pageList);
    }

    @GetMapping(value = "/listCertificateItemByPerkId")
    public Result<?> listCertificateItemByPerkId(MesCertificateItem mesCertificateItem,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        QueryWrapper<MesCertificateItem> queryWrapper = QueryGenerator.initQueryWrapper(mesCertificateItem, req.getParameterMap());
        Page<MesCertificateItem> page = new Page<MesCertificateItem>(pageNo, pageSize);
        IPage<MesCertificateItem> pageList = mesCertificateItemService.page(page, queryWrapper);
        if (pageList.getTotal() == 0) {
            MesCertificatePerk mesCertificatePerk = mesCertificatePerkService.getById(mesCertificateItem.getPerkId());
            String inspectState = "质检完成";
            String unFinish = "未完成";
            if (mesCertificatePerk.getIfFinish().equals(inspectState)) {
                mesCertificatePerk.setIfInput("入库完成");
                mesCertificatePerkService.updateById(mesCertificatePerk);
            } else {
                return Result.error("请先进行质检操作！质检完成后，再进行入库操作");
            }
//			}else if(mesCertificatePerk.getIfFinish().equals(unFinish)){
//				mesCertificatePerk.setIfFinish("完成");
//				mesCertificatePerkService.updateById(mesCertificatePerk);
//			}
            String purchaseId = mesCertificatePerk.getPurchaseId();//采购订单id
            MesOrderPurchase purchaseOrder = transactionClient.getOrderPurchaseById(purchaseId);
            String state = purchaseOrder.getIfFinish();
            if (StringUtils.isNotBlank(state)) {
                String receiveState = "收货完成";
                if (state.equals(receiveState)) {
                    mesCertificatePerk.setIfFinish("质检完成");
                    mesCertificatePerkService.updateById(mesCertificatePerk);
                }
            }
        }
        return Result.ok(pageList);
    }

    /**
     * 远程调用模块，通过id获取物料凭证项目的数据
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryCertificateItemById")
    public MesCertificateItem queryCertificateItemById(@RequestParam(name = "id", required = true) String id) {
        MesCertificateItem mesCertificateItem = mesCertificateItemService.getById(id);
        return mesCertificateItem;
    }

    @PostMapping(value = "/queryCertificateItemByWrapper")
    public MesCertificateItem queryCertificateItemByWrapper(@RequestBody QueryWrapper<MesCertificateItem> w1) {
        MesCertificateItem mesCertificateItem = mesCertificateItemService.getOne(w1);
        return mesCertificateItem;
    }

    /**
     * 远程调用模块，通过id获取物料凭证抬头的数据
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/getCertificateById")
    public MesCertificatePerk getCertificateById(@RequestParam(name = "id", required = true) String id) {
        MesCertificatePerk mesCertificatePerk = mesCertificatePerkService.getById(id);
        return mesCertificatePerk;
    }


    /**
     * 远程调用模块，编辑物料凭证抬头
     *
     * @param mesCertificatePerk
     * @return
     */
    @PutMapping(value = "/editCertificate")
    public String editCertificate(@RequestBody MesCertificatePerk mesCertificatePerk) {
        mesCertificatePerkService.updateById(mesCertificatePerk);
        return "编辑成功!";
    }

    /**
     * 远程调用模块，编辑物料凭证项目
     *
     * @param mesCertificateItem
     * @return
     */
    @PutMapping(value = "/editCertificateItem")
    public String editCertificateItem(@RequestBody MesCertificateItem mesCertificateItem) {
        mesCertificateItemService.updateById(mesCertificateItem);
        return "编辑成功!";
    }

    /**
     * 添加
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-添加")
    @ApiOperation(value = "物料凭证项目-添加", notes = "物料凭证项目-添加")
    @PostMapping(value = "/addCertificateItem")
    public Result<?> addCertificateItem(@RequestBody MesCertificateItem mesCertificateItem) {
        MesCertificateItem certificateItem = mesCertificateItemService.getById(mesCertificateItem.getId());
        BigDecimal unstorageNum = new BigDecimal(certificateItem.getUnstorageNum());//未入库数量
        BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//录入数量
        BigDecimal remainNum = unstorageNum.subtract(inputNum);//未入库数量-录入数量
        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {//remainNum小于0
            return Result.error("数量不符！请检查！");
        } else if (remainNum.compareTo(BigDecimal.ZERO) == 0) {//remainNum等于0
            certificateItem.setIfStorage("是");//已入库
            certificateItem.setUnstorageNum(remainNum.toString());//未入库数量
            mesCertificateItemService.updateById(certificateItem);
        } else {//remainNum大于0
            certificateItem.setUnstorageNum(remainNum.toString());//未入库数量
            mesCertificateItemService.updateById(certificateItem);
        }
        // 105 入库
        if (StringUtils.isNotBlank(mesCertificateItem.getPerkId()) && mesCertificateItem.getMobileCode().equals("105")) {
            //移动编号为105时，类型未入库，以物料料号为索引，如果库存表里找不到数据则新增库存数据，找到则修改库存数据
            QueryWrapper<MesStockManage> stockManageWrapper = new QueryWrapper<>();
            stockManageWrapper.eq("materiel_code", certificateItem.getMaterielCode());
            MesStockManage stock = mesStockManageService.getOne(stockManageWrapper);
            if (stock == null) {
                MesStockManage mesStock = new MesStockManage();
                BeanUtils.copyProperties(certificateItem, mesStock);
                mesStock.setId(null);//主键设置为null
                mesStock.setCreateBy(null);//创建人设置为null
                mesStock.setCreateTime(null);//创建时间设置为null
                mesStock.setMaterielGague(certificateItem.getMaterielGauge());//物料规格
                mesStock.setStoreName(certificateItem.getStorageSite());//仓库名称
                mesStock.setStockNum(mesCertificateItem.getInputNum());//库存数量
                mesStockManageService.save(mesStock);
            } else {
                BigDecimal stockNum = new BigDecimal(stock.getStockNum());//原有的库存数量
                BigDecimal receiveNum = new BigDecimal(mesCertificateItem.getInputNum());//入库数量
                BigDecimal totalNum = stockNum.add(receiveNum);
                stock.setStockNum(totalNum.toString());
                mesStockManageService.updateById(stock);
            }
            String perkId = mesCertificateItem.getPerkId();
            String mobileCode = mesCertificateItem.getMobileCode();
            String mCode = mesCertificateItem.getMaterielCode();
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            wrapper.eq("perk_id", perkId).eq("mobile_code", mobileCode).eq("materiel_code", mCode);
            MesCertificateItem certificateItem1 = mesCertificateItemService.getOne(wrapper);
            if (certificateItem1 != null) {
                BigDecimal oldNum = new BigDecimal(certificateItem1.getInputNum());//已有数量
                BigDecimal inputWareNum = new BigDecimal(mesCertificateItem.getInputNum());//入库数量
                BigDecimal newWareNum = oldNum.add(inputWareNum);
                certificateItem1.setInputNum(newWareNum.toString());
                mesCertificateItemService.updateById(certificateItem1);
                return Result.ok(certificateItem1);
            } else {
                certificateItem.setMobileType("入库");
                certificateItem.setReserveCode(certificateItem.getId());
                certificateItem.setId(null);
                certificateItem.setIfStorage("是");
                certificateItem.setStorageSite(mesCertificateItem.getStorageSite());
                certificateItem.setFactoryName(mesCertificateItem.getFactoryName());
                certificateItem.setMobileCode(mesCertificateItem.getMobileCode());
                certificateItem.setInputNum(mesCertificateItem.getInputNum());
                certificateItem.setPerkId(perkId);
                mesCertificateItemService.save(certificateItem);
                return Result.ok(certificateItem);
            }
        }
        //104 退货
        if (StringUtils.isNotBlank(mesCertificateItem.getPerkId()) && mesCertificateItem.getMobileCode().equals("104")) {
            String perkId = mesCertificateItem.getPerkId();//主抬头id
            String mobileCode = mesCertificateItem.getMobileCode();//移动编号
            String mCode = mesCertificateItem.getMaterielCode();//物料编号
            System.err.println(mesCertificateItem.getMaterielCode());
            System.err.println(mesCertificateItem.getMaterielName());
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            wrapper.eq("perk_id", perkId).eq("mobile_code", mobileCode).eq("materiel_code", mCode);
            MesCertificateItem certificateItem2 = mesCertificateItemService.getOne(wrapper);
            if (certificateItem2 != null) {//之前有退货记录的物料
                BigDecimal oldNum = new BigDecimal(certificateItem2.getInputNum());//已有数量
                BigDecimal inputWareNum = new BigDecimal(mesCertificateItem.getInputNum());//录入数量
                BigDecimal newWareNum = oldNum.add(inputWareNum);
                certificateItem2.setInputNum(newWareNum.toString());
                mesCertificateItemService.updateById(certificateItem2);

                String reserveCode = certificateItem2.getReserveCode();//预留编号=上一步物料凭证项目记录ID（扫描收货）
                MesCertificateItem cItem = mesCertificateItemService.getById(reserveCode);
                if (cItem != null) {
                    String orderId = cItem.getReserveCode();//采购订单项目ID
                    MesPurchaseItem purchaseItem = transactionClient.queryMesPurchaseItemById(orderId);
                    if (purchaseItem != null) {//采购订单项目不为空进入
                        System.err.println("你的思路是对的");
                        purchaseItem.setUnreceiveNum(newWareNum.toString());//未收货数量(将退货数量回填)
                        if (purchaseItem.getIfFinish().equals("收货完成")) {//如果之前收货状态为"收货完成"
                            purchaseItem.setIfFinish("未完成");//退货之后修改状态为"未完成"
                            MesOrderPurchase purchase = transactionClient.getOrderPurchaseById(purchaseItem.getPurchaseId());//获取采购订单主表
                            if (purchase != null && purchase.getIfFinish().equals("收货完成")) {
                                purchase.setIfFinish("未完成");//修改采购订单主表状态
                                transactionClient.editPurchase(purchase);//保存采购订单主表修改
                            }
                        }
                        transactionClient.editPurchaseItem(purchaseItem);//保存采购订单子表修改
                    }
                }
                System.err.println(reserveCode);
                return Result.ok(certificateItem2);
            } else {//之前没有退货记录的物料
                String reserveCode = certificateItem.getId();//查询出来的物料凭证项目ID
                BigDecimal returnNum = new BigDecimal(mesCertificateItem.getInputNum());//提交过来的"录入数量"
                MesCertificateItem cItem = mesCertificateItemService.getById(reserveCode);//获取扫描收货的物料凭证项目记录
                if (cItem != null) {//和上面流程一样
                    String orderId = cItem.getReserveCode();
                    MesPurchaseItem purchaseItem = transactionClient.queryMesPurchaseItemById(orderId);
                    if (purchaseItem != null) {
                        System.err.println("你的思路是对的");
                        BigDecimal originalNum = new BigDecimal(purchaseItem.getUnreceiveNum());
                        BigDecimal oldUnreceiveNum = originalNum.add(returnNum);
                        purchaseItem.setUnreceiveNum(oldUnreceiveNum.toString());
                        if (purchaseItem.getIfFinish().equals("收货完成")) {
                            purchaseItem.setIfFinish("未完成");
                            MesOrderPurchase purchase = transactionClient.getOrderPurchaseById(purchaseItem.getPurchaseId());
                            if (purchase != null && purchase.getIfFinish().equals("收货完成")) {
                                purchase.setIfFinish("未完成");
                                transactionClient.editPurchase(purchase);
                            }
                        }
                        transactionClient.editPurchaseItem(purchaseItem);
                    }
                }
                System.err.println(reserveCode);

                certificateItem.setMobileType("退货");
                certificateItem.setReserveCode(certificateItem.getId());
                certificateItem.setId(null);
                certificateItem.setIfStorage("是");
                certificateItem.setStorageSite(mesCertificateItem.getStorageSite());
                certificateItem.setFactoryName(mesCertificateItem.getFactoryName());
                certificateItem.setMobileCode(mesCertificateItem.getMobileCode());
                certificateItem.setInputNum(returnNum.toString());
                certificateItem.setPerkId(perkId);
                mesCertificateItemService.save(certificateItem);//保存退货记录
                return Result.ok(certificateItem);
            }

        }

        if (mesCertificateItem.getMobileCode().equals("103")) {
            certificateItem.setMobileType("收货");
        } else if (mesCertificateItem.getMobileCode().equals("104")) {
            certificateItem.setMobileType("退货");
        }

        certificateItem.setReserveCode(certificateItem.getId());
        certificateItem.setId(null);
        certificateItem.setIfStorage("是");
        certificateItem.setStorageSite(mesCertificateItem.getStorageSite());
        certificateItem.setFactoryName(mesCertificateItem.getFactoryName());
        certificateItem.setMobileCode(mesCertificateItem.getMobileCode());
        certificateItem.setInputNum(mesCertificateItem.getInputNum());
        mesCertificateItemService.save(certificateItem);
        return Result.ok(certificateItem);
    }

    /**
     * 物料凭证项目-分批次退货
     */
    @AutoLog(value = "物料凭证项目-分批次退货")
    @ApiOperation(value = "物料凭证项目-分批次退货", notes = "物料凭证项目-分批次退货(传入：ID 和 returnNum)")
    @PostMapping(value = "/ReturnsInBatches")
    public Result<?> ReturnsInBatches(@RequestBody MesCertificateItem mesCertificateItem) {
        MesCertificateItem oldCertificateItem = mesCertificateItemService.getById(mesCertificateItem.getId());
        MaterielRetreatRecord materielRetreatRecord = new MaterielRetreatRecord();
        this.setParam(materielRetreatRecord, oldCertificateItem, mesCertificateItem);
        Result<?> result = inspectClient.add(materielRetreatRecord);
        if (result.isSuccess()) {
            oldCertificateItem.setInputNum(this.calculateTheDifference(oldCertificateItem.getInputNum(), mesCertificateItem.getReturnNum()));
            oldCertificateItem.setUnstorageNum(this.calculateTheSum(oldCertificateItem.getUnstorageNum(), mesCertificateItem.getReturnNum()));
            mesCertificateItemService.updateById(oldCertificateItem);
            MesPurchaseItem purchaseItem = transactionClient.queryMesPurchaseItemById(oldCertificateItem.getReserveCode());
            if (purchaseItem != null) {
                System.err.println("你的思路是对的");
                purchaseItem.setUnreceiveNum(this.calculateTheSum(purchaseItem.getUnreceiveNum(), mesCertificateItem.getReturnNum()));
                if (purchaseItem.getIfFinish().equals("收货完成")) {
                    purchaseItem.setIfFinish("未完成");
                    MesOrderPurchase purchase = transactionClient.getOrderPurchaseById(purchaseItem.getPurchaseId());
                    if (purchase != null && purchase.getIfFinish().equals("收货完成")) {
                        purchase.setIfFinish("未完成");
                        transactionClient.editPurchase(purchase);
                    }
                }
                transactionClient.editPurchaseItem(purchaseItem);
            }
        }
        return result;
    }

    /**
     * app扫描入库
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app扫描入库")
    @ApiOperation(value = "物料凭证项目-app扫描入库", notes = "物料凭证项目-app扫描入库")
    @PostMapping(value = "/scanEnterStore")
    public Result<?> scanEnterStore(@RequestBody MesCertificateItem mesCertificateItem) {
        String perkId = mesCertificateItem.getPerkId();//凭证抬头id
        String mobileType = mesCertificateItem.getMobileType();//移动类型
        String materielCode = mesCertificateItem.getMaterielCode();//料号
        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType).eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }
            MesCertificateItem certificateItem = mesCertificateItemService.getOne(wrapper);
            String mobileCode = "106";
            if (certificateItem == null) {
                //106 扫描入库
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    //通过预留编号（物料凭证项目id），获取物料凭证项目数据
                    MesCertificateItem certificateItem1 = mesCertificateItemService.getById(mesCertificateItem.getReserveCode());
                    if (certificateItem1 != null) {
                        BeanUtils.copyProperties(certificateItem1, mesCertificateItem);
                        mesCertificateItem.setId(null);//主键设置为null
                        mesCertificateItem.setInputNum("0");
                        mesCertificateItem.setMobileCode(mobileCode);
                        mesCertificateItem.setMobileType("扫描入库");
                        mesCertificateItem.setReserveCode(certificateItem1.getId());
                        mesCertificateItem.setIfInspect("是");
                        mesCertificateItem.setIfStorage("是");
                        mesCertificateItemService.save(mesCertificateItem);
                        return Result.ok(mesCertificateItem);
                    } else {
                        return Result.error("没有找到物料凭证的收货数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("扫描入库时移动编号不等于106！请检查");
                }
            } else {
                if (certificateItem.getMobileCode().equals(mobileCode)) {
                    return Result.ok(certificateItem);
                } else {
                    return Result.error("扫描入库时移动编号不等于106！请检查");
                }
            }
        } else {
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
    }

    /**
     * app收货
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app收货")
    @ApiOperation(value = "物料凭证项目-app收货", notes = "物料凭证项目-app收货")
    @PostMapping(value = "/addReceiveItem")
    public Result<?> addReceiveItem(@RequestBody MesCertificateItem mesCertificateItem) {
        return Result.ok(mesCertificatePerkService.addReceiveItem(mesCertificateItem));
    }


    /**
     * app制令单发料
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app制令单发料")
    @ApiOperation(value = "物料凭证项目-app制令单发料", notes = "物料凭证项目-app制令单发料")
    @PostMapping(value = "/addSendMateriel")
    public Result<?> addSendMateriel(@RequestBody MesCertificateItem mesCertificateItem) {
        String perkId = mesCertificateItem.getPerkId();//抬头id
        String mobileType = mesCertificateItem.getMobileType();//移动类型
        String materielCode = mesCertificateItem.getMaterielCode();//物料编号
        String query5 = mesCertificateItem.getQuery5();//制令单id

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//当前登录用户

        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            //物料凭证项目是否有
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType).eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }
            MesCertificateItem certificateItem = mesCertificateItemService.getOne(wrapper);
            String mobileCode = "261";
            MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
            MesMaterielOccupy mesMaterielOccupy = new MesMaterielOccupy();
            if (certificateItem == null) {
                certificateItem = mesCertificateItem;
                //261 制令单发料
                if (mobileCode.equals(certificateItem.getMobileCode())) {
                    //通过预留编号，获取制令单BOM表的相应数据
                    if (commandbillPitem != null) {
                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                        if (StringUtils.isNotBlank(certificateItem.getInputNum())) {
                            String orderId = commandbillPitem.getProorderId();//生产订单id
                            String mCode = commandbillPitem.getMaterielCode();//物料料号
                            String inputNum = certificateItem.getInputNum();//发料数量
                            //制令单发料可以超发，先扣除领料单领取的数量；若超过领料数量，再从库存里扣除
                            QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                            materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                            mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                            if (mesMaterielOccupy != null) {
                                BigDecimal unUsedNum = BigDecimal.ZERO;//未使用数量
                                BigDecimal requireNum = new BigDecimal(inputNum);//发料数量
                                if (unUsedNum.compareTo(requireNum) == -1) {//物料超发
                                    BigDecimal usedStockNum = requireNum.subtract(unUsedNum);//超发的数量
                                    /*QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                                    queryWrapper.eq("materiel_code", mCode);
                                    MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);*/
                                    MesCommandbillInfo commandbillInfo = produceClient.getById(commandbillPitem.getCommandbillId());
                                    if (StringUtils.isBlank(commandbillInfo.getClientName())){
                                        return Result.error("制令单客戶名稱爲空！请检查！");
                                    }
                                    MesStockManage stockManage = mesStockManageService.queryByMcodeAndClient(mCode, commandbillInfo.getClientName());
                                    if (stockManage == null) {
                                        return Result.error("查不到库存数据！请检查！");
                                    } else {
                                        BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());//库存数量
                                        BigDecimal minimum = new BigDecimal(stockManage.getMinimum());//库存临界点
                                        BigDecimal remainNum = stockNum.subtract(usedStockNum);//剩余数量=库存数量-超发数量
                                        //如果库存数量小于0，则提示库存数量不足。反之，将剩余数量，更新到库存上
                                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                                            return Result.error("库存数量不足！请检查！");
                                        } else {
                                            stockManage.setStockNum(remainNum.toString());//新的库存数量 = 剩余数量
                                            mesStockManageService.updateById(stockManage);
                                            //如果库存数量小于库存临界点，则给用户发送消息提醒
                                            if (remainNum.compareTo(minimum) < 1) {
                                                //测试时，向当前登录用户发送消息提醒；正式上线后，需要向采购人员（溢哲渝设定）发送库存临界点警告
                                                systemClient.sendMessage(sysUser.getUsername(), stockManage.getMaterielName());
                                            }
                                            BigDecimal num = deliveryNum.add(requireNum);//新的发料数量 = 原有数量+发料数量
                                            commandbillPitem.setDeliveryNum(num.toString());
                                            commandbillPitem.setIfGlaze("未上料");
                                            produceClient.editComitem(commandbillPitem);
                                            //更新领料表数据
                                            mesMaterielOccupy.setOccupyPerson(sysUser.getUsername());//发料人
                                            mesMaterielOccupy.setSendNum(num.toString());//发料数量
                                            mesMaterielOccupy.setOccupyTime(DateUtils.getDate());//发料时间
                                            mesMaterielOccupy.setUnusedNum("0");
                                            mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                        }
                                    }
                                } else {//未超发
                                    BigDecimal remainNum = unUsedNum.subtract(requireNum);//剩余数量 = 未领用数量-发料数量
                                    BigDecimal num = deliveryNum.add(requireNum);//新的发料数量 = 原有数量+发料数量
                                    commandbillPitem.setDeliveryNum(num.toString());
                                    commandbillPitem.setIfGlaze("未上料");
                                    produceClient.editComitem(commandbillPitem);
                                    //更新领料表数据
                                    mesMaterielOccupy.setOccupyPerson(sysUser.getUsername());//发料人
                                    mesMaterielOccupy.setSendNum(num.toString());//发料数量
                                    mesMaterielOccupy.setOccupyTime(DateUtils.getDate());//发料时间
                                    mesMaterielOccupy.setUnusedNum(remainNum.toString());//未使用数量
                                    mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                }
                            } else {
                                return Result.error("领料数据为空！请检查！");
                            }
                        }
                        BeanUtils.copyProperties(commandbillPitem, certificateItem);
                        certificateItem.setId(null);//主键设置为null
                        certificateItem.setCreateBy(sysUser.getUsername());//创建人
                        certificateItem.setCreateTime(DateUtils.getDate());//创建时间
                        certificateItem.setInputUnit(commandbillPitem.getCountUnit());//单位
                        mesCertificateItemService.save(certificateItem);
                        //判断物料发送完了没有，修改状态为已完成
                        produceClient.getCommandBomBycommandbillId(query5,certificateItem.getMaterielCode());

//						 //存发料日志 已弃用
//						 MesCommandbillDlog mesCommandbillDlog = new MesCommandbillDlog();
//						 //获取用户登录信息
//						 mesCommandbillDlog.setCreateBy(sysUser.getUsername());//创建人
//						 mesCommandbillDlog.setCreateTime(DateUtils.getDate());//创建者
//						 mesCommandbillDlog.setCommandbillId(query5);//制令单id
//						 mesCommandbillDlog.setCommandbillCode(null);//制令单code
//						 mesCommandbillDlog.setMaterielName(mesCertificateItem.getMaterielName());//物料编号
//						 BigDecimal materielNum = new BigDecimal(mesCertificateItem.getInputNum());
//						 mesCommandbillDlog.setMaterielNum(materielNum);//数量
//						 mesCommandbillDlog.setMaterielType(mesCertificateItem.getMobileType());//类型
//						 mesCommandbillDlog.setPitemId(mesCertificateItem.getReserveCode());//制令单bom编号
//						 produceClient.addDLog(mesCommandbillDlog);

                        //return Result.ok(certificateItem);
                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("制令单发料时移动编号不等于261！请检查");
                }
            } else {
                if (certificateItem.getMobileCode().equals(mobileCode)) {
                    //通过预留编号，获取制令单BOM表的相应数据
                    //MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    if (commandbillPitem != null) {
                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                        if (StringUtils.isNotBlank(mesCertificateItem.getInputNum())) {
                            String orderId = commandbillPitem.getProorderId();//生产订单id
                            String mCode = commandbillPitem.getMaterielCode();//物料料号
                            String inputNum = mesCertificateItem.getInputNum();//发料数量
                            //制令单发料可以超发，先扣除领料单领取的数量；若超过领料数量，再从库存里扣除
                            QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                            materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                            mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                            if (mesMaterielOccupy != null) {
//								BigDecimal occupyNum = new BigDecimal(mesMaterielOccupy.getOccupyNum());//领用数量
                                BigDecimal unUsedNum = new BigDecimal(mesMaterielOccupy.getUnusedNum());//未使用数量
                                BigDecimal requireNum = new BigDecimal(inputNum);//发料数量
                                BigDecimal oldNum = new BigDecimal(certificateItem.getInputNum());//物料凭证数量
                                if (unUsedNum.compareTo(requireNum) == -1) {//物料超发
                                    System.err.println("你的思路是对的！");
                                    BigDecimal usedStockNum = requireNum.subtract(unUsedNum);//超发的数量
                                    QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                                    queryWrapper.eq("materiel_code", mCode);
                                    MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                                    if (stockManage == null) {
                                        return Result.error("查不到库存数据！请检查！");
                                    } else {
                                        BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());//库存数量
                                        BigDecimal minimum = new BigDecimal(stockManage.getMinimum());//库存临界点
                                        BigDecimal remainNum = stockNum.subtract(usedStockNum);//剩余数量=库存数量-超发数量
                                        //如果库存数量小于0，则提示库存数量不足。反之，将剩余数量，更新到库存上
                                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                                            return Result.error("库存数量不足！请检查！");
                                        } else {
                                            stockManage.setStockNum(remainNum + "");//新的库存数量 = 剩余数量
                                            mesStockManageService.updateById(stockManage);
                                            //如果库存数量小于库存临界点，则给用户发送消息提醒
                                            if (remainNum.compareTo(minimum) < 1) {
                                                //测试时，向当前登录用户发送消息提醒；正式上线后，需要向采购人员（溢哲渝设定）发送库存临界点警告
                                                systemClient.sendMessage(sysUser.getUsername(), stockManage.getMaterielName());
                                            }
                                            BigDecimal num = deliveryNum.add(requireNum);//新的发料数量 = 原有数量+发料数量
                                            commandbillPitem.setDeliveryNum(num.toString());//已发料数量
                                            commandbillPitem.setIfGlaze("未上料");
                                            produceClient.editComitem(commandbillPitem);
                                            //更新领料表数据
                                            mesMaterielOccupy.setUnusedNum("0");//未使用数量
                                            mesMaterielOccupy.setOccupyPerson(sysUser.getUsername());//发料人
                                            mesMaterielOccupy.setSendNum(num.toString());//发料数量
                                            mesMaterielOccupy.setOccupyTime(DateUtils.getDate());//发料时间
                                            mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                            //更新物料凭证表数据
                                            BigDecimal newNum = oldNum.add(requireNum);
                                            certificateItem.setInputNum(newNum.toString());//新物料凭证数量 = 旧数量 + 发料数量
                                        }
                                    }
                                } else {//未超发
                                    BigDecimal remainNum = unUsedNum.subtract(requireNum);//剩余数量 = 未领用数量-发料数量
                                    BigDecimal num = deliveryNum.add(requireNum);//新的发料数量 = 原有数量+发料数量
                                    commandbillPitem.setDeliveryNum(num.toString());
                                    commandbillPitem.setIfGlaze("未上料");
                                    produceClient.editComitem(commandbillPitem);
                                    //更新领料表数据
                                    mesMaterielOccupy.setOccupyPerson(sysUser.getUsername());//发料人
                                    mesMaterielOccupy.setSendNum(num.toString());//发料数量
                                    mesMaterielOccupy.setOccupyTime(DateUtils.getDate());//发料时间
                                    mesMaterielOccupy.setUnusedNum(remainNum.toString());//未使用数量
                                    mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                    //更新物料凭证表数据
                                    BigDecimal newNum = oldNum.add(requireNum);
                                    certificateItem.setInputNum(newNum.toString());
                                }
                            } else {
                                return Result.error("领料数据为空！请检查！");
                            }
                        }
                        mesCertificateItemService.updateById(certificateItem);
                        //判断物料发送完了没有，修改状态为已完成
                        produceClient.getCommandBomBycommandbillId(query5,certificateItem.getMaterielCode());

                        //存发料日志 已弃用
//						 MesCommandbillDlog mesCommandbillDlog = new MesCommandbillDlog();
//
//						 mesCommandbillDlog.setCreateBy(sysUser.getUsername());//创建人
//						 mesCommandbillDlog.setCreateTime(DateUtils.getDate());//创建者
//						 mesCommandbillDlog.setCommandbillId(query5);//制令单id
//						 mesCommandbillDlog.setCommandbillCode(null);//制令单code
//						 mesCommandbillDlog.setMaterielName(mesCertificateItem.getMaterielName());//物料编号
//						 BigDecimal materielNum = new BigDecimal(mesCertificateItem.getInputNum());
//						 mesCommandbillDlog.setMaterielNum(materielNum);//数量
//						 mesCommandbillDlog.setMaterielType(mesCertificateItem.getMobileType());//类型
//						 mesCommandbillDlog.setPitemId(mesCertificateItem.getReserveCode());//制令单bom编号
//						 produceClient.addDLog(mesCommandbillDlog);

                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("制令单发料时移动编号不等于261！请检查");
                }
            }

            String inWareNum = mesStorageWholesaleService.getSumByInWareNum(commandbillPitem.getId());//批号交易扫描发料数量
            if (!inWareNum.equals(mesMaterielOccupy.getSendNum())) {
                mesMaterielOccupy.setSendNum(inWareNum);
                mesMaterielOccupyService.updateById(mesMaterielOccupy);
            }
            if(!inWareNum.equals(commandbillPitem.getDeliveryNum())){
                commandbillPitem.setDeliveryNum(inWareNum);
                produceClient.editComitem(commandbillPitem);
            }

            return Result.ok(certificateItem);
        } else {
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
    }

    /**
     * app制令单入库
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app制令单入库")
    @ApiOperation(value = "物料凭证项目-app制令单入库", notes = "物料凭证项目-app制令单入库")
    @PostMapping(value = "/addEnterItem")
    public Result<?> addEnterItem(@RequestBody MesCertificateItem mesCertificateItem) {
        String perkId = mesCertificateItem.getPerkId();
        String mobileType = mesCertificateItem.getMobileType();
        String materielCode = mesCertificateItem.getMaterielCode();

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//当前登录用户

        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType).eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }
            MesCertificateItem certificateItem = mesCertificateItemService.getOne(wrapper);
            System.out.println("======app制令单入库=====certificateItem==" + certificateItem);
            String mobileCode = "262";
            if (certificateItem == null) {
                //262 制令单入库
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    // 通过预留编号（生产订单ID），获取生产订单的相应数据
                    MesOrderProduce mesOrderProduce = transactionClient.queryMesProduceById(mesCertificateItem.getReserveCode());
                    System.out.println("======app制令单入库 生产信息=====mesOrderProduce==" + mesOrderProduce);
                    if (mesOrderProduce != null) {
                        BigDecimal grossNum = new BigDecimal(mesOrderProduce.getGrossAccount());//生产订单的总数量
                        BigDecimal receiveNum = new BigDecimal(mesCertificateItem.getInputNum()); //物料凭证的录入数量
                        if (StringUtils.isNotBlank(mesCertificateItem.getCommandId())) {
                            MesCommandbillInfo mesCommandbillInfo = produceClient.getById(mesCertificateItem.getCommandId());//制令单信息
                            BigDecimal uninputNum = new BigDecimal(mesCommandbillInfo.getUninputNum());//未入库数量
                            BigDecimal remainNum = uninputNum.subtract(receiveNum);
                            if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                                return Result.error("请检查入库数量是否正确！");
                            } else if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                                mesCommandbillInfo.setUninputNum(remainNum.toString());
                                mesCommandbillInfo.setInputState("入库完成");
                                produceClient.editCommand(mesCommandbillInfo);

                                //修改状态为未完成，才能继续进行质检
                                MesCertificatePerk certificatePerk = mesCertificatePerkService.getById(perkId);
                                if (certificatePerk != null) {
                                    certificatePerk.setIfFinish("未完成");
                                    mesCertificatePerkService.updateById(certificatePerk);
                                }
                                //全部入库，改变生产订单的状态，入库完成
                                mesOrderProduce.setRemainNum("0");
                                mesOrderProduce.setInputNum(grossNum.toString());
                                mesOrderProduce.setState("入库完成");
                                transactionClient.editProduce(mesOrderProduce);
                            } else {
                                mesCommandbillInfo.setUninputNum(remainNum.toString());
                                produceClient.editCommand(mesCommandbillInfo);

                                //修改状态为未完成，才能继续进行质检
                                MesCertificatePerk certificatePerk = mesCertificatePerkService.getById(perkId);
                                if (certificatePerk != null) {
                                    certificatePerk.setIfFinish("未完成");
                                    mesCertificatePerkService.updateById(certificatePerk);
                                }
                                //部分入库，修改生产订单的入库数量与剩余数量
                                mesOrderProduce.setRemainNum(remainNum.toString());
                                BigDecimal inputNum = grossNum.subtract(remainNum);
                                mesOrderProduce.setInputNum(inputNum.toString());
                                transactionClient.editProduce(mesOrderProduce);

                            }
                        }
                        mesCertificateItem.setIfInspect("否");
                        BeanUtils.copyProperties(mesOrderProduce, mesCertificateItem);
                        mesCertificateItem.setId(null);//主键设置为null
                        mesCertificateItem.setCreateBy(sysUser.getUsername());//创建人设置为null
                        mesCertificateItem.setCreateTime(DateUtils.getDate());//创建时间设置为null
                        mesCertificateItem.setMaterielGauge(mesOrderProduce.getGauge());//物料规格
                        mesCertificateItem.setInputUnit(mesOrderProduce.getUnit());// 单位

                        QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("materiel_code", mesOrderProduce.getMaterielCode());
                        MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                        if (stockManage != null) {
                            BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                            BigDecimal newStock = stockNum.add(receiveNum);
                            stockManage.setStockNum(newStock.toString());
                            mesStockManageService.updateById(stockManage);
                        } else {
                            MesStockManage mesStockManage = new MesStockManage();
                            BeanUtils.copyProperties(mesOrderProduce, mesStockManage);
                            mesStockManage.setId(null);//设置主键为null
                            mesStockManage.setCreateBy(sysUser.getUsername());//创建人设置
                            mesStockManage.setCreateTime(DateUtils.getDate());//创建时间设置
                            mesStockManage.setMaterielGague(mesOrderProduce.getGauge());//物料规格
                            mesStockManage.setStoreName(mesOrderProduce.getStorageSite());//存储位置
                            mesStockManage.setStockNum(receiveNum + "");
                            MesChiefdataMateriel mater = systemClient.queryByMcode(mesStockManage.getMaterielCode());
                            if (mater != null) {
                                mesStockManage.setQuery5(mater.getMaterielType());
                            }
                            mesStockManageService.save(mesStockManage);
                        }
                        mesCertificateItemService.save(mesCertificateItem);

                        return Result.ok(mesCertificateItem);
                    } else {
                        return Result.error("没有找到生产订单的数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("制令单入库时移动编号不等于262！请检查");
                }
            } else {
                if (certificateItem.getMobileCode().equals(mobileCode)) {
                    // 通过预留编号（生产订单ID），获取生产订单的相应数据
                    MesOrderProduce mesOrderProduce = transactionClient.queryMesProduceById(mesCertificateItem.getReserveCode());
                    if (mesOrderProduce != null) {
                        BigDecimal grossNum = new BigDecimal(mesOrderProduce.getGrossAccount());//生产订单的总数量
                        BigDecimal receiveNum = new BigDecimal(mesCertificateItem.getInputNum());//入库数量
                        if (StringUtils.isNotBlank(mesCertificateItem.getCommandId())) {
                            MesCommandbillInfo mesCommandbillInfo = produceClient.getById(mesCertificateItem.getCommandId());
                            BigDecimal oldNum = new BigDecimal(certificateItem.getInputNum());//已有数量
                            BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());
                            BigDecimal uninputNum = new BigDecimal(mesCommandbillInfo.getUninputNum());//未入库数量
                            BigDecimal remainNum = uninputNum.subtract(receiveNum);
                            if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                                return Result.error("请检查入库数量是否正确！");
                            } else if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                                mesCommandbillInfo.setUninputNum(remainNum.toString());
                                mesCommandbillInfo.setInputState("入库完成");
                                produceClient.editCommand(mesCommandbillInfo);
                                BigDecimal inputNumNew = oldNum.add(inputNum);
                                certificateItem.setInputNum(inputNumNew.toString());

                                //修改状态为未完成，才能继续进行质检
                                MesCertificatePerk certificatePerk = mesCertificatePerkService.getById(perkId);
                                if (certificatePerk != null) {
                                    certificatePerk.setIfFinish("未完成");
                                    mesCertificatePerkService.updateById(certificatePerk);
                                }
                                //全部入库，改变生产订单的状态，入库完成
                                mesOrderProduce.setRemainNum("0");
                                mesOrderProduce.setInputNum(grossNum.toString());
                                mesOrderProduce.setState("入库完成");
                                transactionClient.editProduce(mesOrderProduce);
                            } else {
                                mesCommandbillInfo.setUninputNum(remainNum.toString());
                                produceClient.editCommand(mesCommandbillInfo);
                                BigDecimal inputNumNew = oldNum.add(inputNum);
                                certificateItem.setInputNum(inputNumNew.toString());

                                //修改状态为未完成，才能继续进行质检
                                MesCertificatePerk certificatePerk = mesCertificatePerkService.getById(perkId);
                                if (certificatePerk != null) {
                                    certificatePerk.setIfFinish("未完成");
                                    mesCertificatePerkService.updateById(certificatePerk);
                                }
                                //部分入库，修改生产订单的入库数量与剩余数量
                                mesOrderProduce.setRemainNum(remainNum.toString());
                                BigDecimal storageNum = grossNum.subtract(remainNum);
                                mesOrderProduce.setInputNum(storageNum.toString());
                                transactionClient.editProduce(mesOrderProduce);
                            }
                        }

                        QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("materiel_code", mesOrderProduce.getMaterielCode());
                        MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                        if (stockManage != null) {
                            BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                            BigDecimal newStock = stockNum.add(receiveNum);
                            stockManage.setStockNum(newStock.toString());
                            mesStockManageService.updateById(stockManage);
                        } else {
                            MesStockManage mesStockManage = new MesStockManage();
                            BeanUtils.copyProperties(mesOrderProduce, mesStockManage);
                            mesStockManage.setId(null);//设置主键为null
                            mesStockManage.setCreateBy(sysUser.getUsername());//设置创建人为null
                            mesStockManage.setCreateTime(DateUtils.getDate());//设置创建时间为null
                            mesStockManage.setMaterielGague(mesOrderProduce.getGauge());
                            mesStockManage.setStoreName(mesOrderProduce.getStorageSite());
                            mesStockManage.setStockNum(receiveNum.toString());
                            MesChiefdataMateriel mater = systemClient.queryByMcode(mesStockManage.getMaterielCode());
                            if (mater != null) {
                                mesStockManage.setQuery5(mater.getMaterielType());
                            }
                            mesStockManageService.save(mesStockManage);
                        }
                        mesCertificateItemService.updateById(certificateItem);
                        return Result.ok(certificateItem);
                    } else {
                        return Result.error("没有找到生产订单的数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("制令单入库时移动编号不等于262！请检查");
                }
            }
        } else {
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
    }

    /**
     * app制令单上料
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app制令单上料")
    @ApiOperation(value = "物料凭证项目-app制令单上料", notes = "物料凭证项目-app制令单上料")
    @PostMapping(value = "/addGlazeMateriel")
    public Result<?> addGlazeMateriel(@RequestBody MesCertificateItem mesCertificateItem) {
        String perkId = mesCertificateItem.getPerkId();
        String mobileType = mesCertificateItem.getMobileType();
        String materielCode = mesCertificateItem.getMaterielCode();
        String query5 = mesCertificateItem.getQuery5();//制令单id

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//当前登录用户

        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType).eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }
            MesCertificateItem certificateItem = mesCertificateItemService.getOne(wrapper);
            String mobileCode = "263";
            if (certificateItem == null) {
                //263 制令单上料
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    if (commandbillPitem != null) {
                        BigDecimal glazeNum = new BigDecimal(commandbillPitem.getUnglazeNum()); //原有数量
                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                        BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//上料数量
                        BigDecimal glazeNewNum = glazeNum.add(inputNum);//已上料数量=原有数量+上料数量
                        //如果已上料数量超过已发料数量，则提示错误数量不符
                        if (glazeNewNum.compareTo(deliveryNum) == 1) {
                            return Result.error("数量不符！请先检查！");
                        } else {
                            commandbillPitem.setUnglazeNum(glazeNewNum.toString());
                            produceClient.editComitem(commandbillPitem);
                        }
                        BeanUtils.copyProperties(commandbillPitem, mesCertificateItem);
                        mesCertificateItem.setId(null);//主键设置为null
                        mesCertificateItem.setCreateBy(sysUser.getUsername());//创建人
                        mesCertificateItem.setCreateTime(DateUtils.getDate());//创建时间
                        mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                        mesCertificateItemService.save(mesCertificateItem);

                        //判断物料发送完了没有，修改状态为已完成
                        produceClient.getCommandBomBycommandbillId(query5,mesCertificateItem.getMaterielCode());
                        return Result.ok(mesCertificateItem);
                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("制令单上料时移动编号不等于263！请检查");
                }
            } else {
                if (certificateItem.getMobileCode().equals(mobileCode)) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    if (commandbillPitem != null) {
                        BigDecimal glazeNum = new BigDecimal(commandbillPitem.getUnglazeNum()); //原有数量
                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                        BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//上料数量
                        BigDecimal glazeNewNum = glazeNum.add(inputNum);//已上料数量=原有数量+上料数量
                        //如果已上料数量超过已发料数量，则提示错误数量不符
                        if (glazeNewNum.compareTo(deliveryNum) == 1) {
                            return Result.error("数量不符！请先检查！");
                        } else {
                            commandbillPitem.setUnglazeNum(glazeNewNum.toString());
                            produceClient.editComitem(commandbillPitem);

                            BigDecimal oldNum = new BigDecimal(certificateItem.getInputNum());//凭证已有数量
                            BigDecimal certificateNum = oldNum.add(inputNum);//凭证新数量 = 凭证已有数量 + 上料数量
                            certificateItem.setInputNum(certificateNum.toString());
                        }
                        mesCertificateItemService.updateById(certificateItem);

                        //判断物料发送完了没有，修改状态为已完成
                        produceClient.getCommandBomBycommandbillId(query5,certificateItem.getMaterielCode());
                        return Result.ok(certificateItem);
                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("制令单上料时移动编号不等于263！请检查");
                }
            }
        } else {
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
    }


    /**
     * app制令单扫描发料/上料
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app制令单扫描发料")
    @ApiOperation(value = "物料凭证项目-app制令单扫描发料", notes = "物料凭证项目-app制令单扫描发料")
    @PostMapping(value = "/scanSendMateriel")
    public Result<?> scanSendMateriel(@RequestBody MesCertificateItem mesCertificateItem) {
        QueryWrapper<MesMaterielOccupy> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("unused_num","0");
        MesMaterielOccupy mesMaterielOccupy = new MesMaterielOccupy();
        mesMaterielOccupy.setUnusedNum("0");
        mesMaterielOccupyService.update(mesMaterielOccupy,queryWrapper);
        String perkId = mesCertificateItem.getPerkId();
        String mobileType = mesCertificateItem.getMobileType();
        String materielCode = mesCertificateItem.getMaterielCode();
        String query5 = mesCertificateItem.getQuery5();//制令单id
        System.out.println("mesCertificateItem====123==" + mesCertificateItem);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//当前登录用户


        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType)
                        .eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }

            MesCertificateItem certificateItem = mesCertificateItemService.getOne(wrapper);
            String mobileCode = "264";
            if (certificateItem == null) {
                //264 制令单扫描发料/上料
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    System.out.println("==commandbillPitem==123====" + commandbillPitem);
                    if (commandbillPitem != null) {
                        if (StringUtils.isNotBlank(query5)&&(!commandbillPitem.getCommandbillId().equals(query5))){
                            return Result.error("凭证抬头已失效，请返回上一级重新创建！");
                        }
                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                        if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                            mesCertificateItem.setInputNum("0");
                        }
                        BeanUtils.copyProperties(commandbillPitem, mesCertificateItem);
                        mesCertificateItem.setId(null);//主键设置
                        mesCertificateItem.setCreateBy(sysUser.getUsername());//创建人设置
                        mesCertificateItem.setCreateTime(DateUtils.getDate());//创建时间设置
                        mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                        mesCertificateItemService.save(mesCertificateItem);

                        //判断物料发送完了没有，修改状态为已完成
                        produceClient.getCommandBomBycommandbillId(query5,mesCertificateItem.getMaterielCode());
                        return Result.ok(mesCertificateItem);
                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("制令单扫描发料/上料时移动编号不等于264！请检查");
                }
            } else {
                if (certificateItem.getMobileCode().equals(mobileCode)) {
                    //判断物料发送完了没有，修改状态为已完成
                    produceClient.getCommandBomBycommandbillId(query5,certificateItem.getMaterielCode());
                    return Result.ok(certificateItem);
                } else {
                    return Result.error("制令单扫发料时移动编号不等于264！请检查");
                }
            }
        } else {
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
    }

    /**
     * app制令单扫描发料/上料
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app制令单扫描上料")
    @ApiOperation(value = "物料凭证项目-app制令单扫描上料", notes = "物料凭证项目-app制令单扫描上料")
    @PostMapping(value = "/scanSendMateriel2")
    public Result<?> scanSendMateriel2(@RequestBody MesCertificateItem mesCertificateItem) {
        //替代料验证
        MesCommandbillInfo commandbillinfo = produceClient.getById(mesCertificateItem.getQuery5());
        List<MesChiefdataReplacematerial> replacematerials = systemClient.queryReplaceCode(commandbillinfo.getMechanismCode(), null, mesCertificateItem.getMaterielCode());
        if (replacematerials.size() > 0) {
            mesCertificateItem.setMaterielCode(replacematerials.get(0).getMainCode());
        }
        //去该制令单下面查找该子表物料信息
        MesCommandbillPitem commandbillPitem = produceClient.getPitemById(mesCertificateItem.getQuery5(), mesCertificateItem.getMaterielCode());
        if (commandbillPitem == null) {
            this.recordErrorOperation("/storage/mesCertificatePerk/scanSendMateriel2", "制令单上料", "物料凭证项目-app制令单扫描上料", "未在该制令单找到该物料，请检查！", commandbillPitem.getCommandbillId());
            return Result.error("未在该制令单找到该物料，请检查！");
        }
        mesCertificateItem.setReserveCode(commandbillPitem.getId());
        //mesCertificateItem.setInputNum(commandbillPitem.getDeliveryNum());
        String perkId = mesCertificateItem.getPerkId();
        String mobileType = mesCertificateItem.getMobileType();
        String materielCode = mesCertificateItem.getMaterielCode();
        String query5 = mesCertificateItem.getQuery5();//制令单id
        System.out.println("mesCertificateItem====123==" + mesCertificateItem);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//当前登录用户

        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType)
                        .eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }

            List<MesCertificateItem> list = mesCertificateItemService.list(wrapper);
            String mobileCode = "264";
            MesCertificateItem certificateItem = null;
            if (list.size() > 0) {
                certificateItem = list.get(0);
            }
            if (certificateItem == null) {
                //264 制令单扫描发料/上料
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    //通过预留编号，获取制令单BOM表的相应数据
                    System.out.println("==commandbillPitem==123====" + commandbillPitem);
                    if (commandbillPitem != null && StringUtils.isNotBlank(commandbillPitem.getDeliveryNum())) {
                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                        if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                            mesCertificateItem.setInputNum("0");
                        }
                        BeanUtils.copyProperties(commandbillPitem, mesCertificateItem);
                        mesCertificateItem.setId(null);//主键设置
                        mesCertificateItem.setCreateBy(sysUser.getUsername());//创建人设置
                        mesCertificateItem.setCreateTime(DateUtils.getDate());//创建时间设置
                        mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                        mesCertificateItemService.save(mesCertificateItem);

                        //判断物料发送完了没有，修改状态为已完成
                        produceClient.getCommandBomBycommandbillId(query5,mesCertificateItem.getMaterielCode());
                        return Result.ok(mesCertificateItem);
                    } else {
                        this.recordErrorOperation("/storage/mesCertificatePerk/scanSendMateriel2", "制令单上料", "物料凭证项目-app制令单扫描上料", "没有找到制令单BOM的数据！请检查预留编号是否正确！", commandbillPitem.getCommandbillId());
                        return Result.error("没有找到制令单BOM的数据！请检查预留编号是否正确！");
                    }
                } else {
                    this.recordErrorOperation("/storage/mesCertificatePerk/scanSendMateriel2", "制令单上料", "物料凭证项目-app制令单扫描上料", "制令单扫描发料/上料时移动编号不等于264！请检查", commandbillPitem.getCommandbillId());
                    return Result.error("制令单扫描发料/上料时移动编号不等于264！请检查");
                }
            } else {
                if (certificateItem.getMobileCode().equals(mobileCode)) {

                    //判断物料发送完了没有，修改状态为已完成
                    produceClient.getCommandBomBycommandbillId(query5,certificateItem.getMaterielCode());
                    return Result.ok(certificateItem);
                } else {
                    this.recordErrorOperation("/storage/mesCertificatePerk/scanSendMateriel2", "制令单上料", "物料凭证项目-app制令单扫描上料", "制令单扫发料时移动编号不等于264！请检查！", commandbillPitem.getCommandbillId());
                    return Result.error("制令单扫发料时移动编号不等于264！请检查");
                }
            }
        } else {
            this.recordErrorOperation("/storage/mesCertificatePerk/scanSendMateriel2", "制令单上料", "物料凭证项目-app制令单扫描上料", "没有找到凭证抬头ID和移动类型！请检查", commandbillPitem.getCommandbillId());
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
    }

    /**
     * app制令单退料
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app制令单退料")
    @ApiOperation(value = "物料凭证项目-app制令单退料", notes = "物料凭证项目-app制令单退料")
    @PostMapping(value = "/addReturnMateriel")
    public Result<?> addReturnMateriel(@RequestBody MesCertificateItem mesCertificateItem) {
        String perkId = mesCertificateItem.getPerkId();
        String mobileType = mesCertificateItem.getMobileType();
        String materielCode = mesCertificateItem.getMaterielCode();
        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType).eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }
            MesCertificateItem certificateItem = mesCertificateItemService.getOne(wrapper);
            String mobileCode = "265";
            if (certificateItem == null) {
                //265 制令单退料
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    if (commandbillPitem != null) {
                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                        BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum()); //退料数量
                        BigDecimal remainNum = deliveryNum.subtract(inputNum); //剩余数量 = 已发料数量 - 退料数量
                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                            return Result.error("数量不符!请检查！");
                        } else {
                            mesCertificateItem.setInputNum(inputNum.toString());
                            //退料操作
                            if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(commandbillPitem.getMaterielCode())) {
                                //通过订单id与物料料号，查询领料表信息
                                String orderId = commandbillPitem.getProorderId();//生产订单id
                                MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                String mCode = commandbillPitem.getMaterielCode();//物料料号
                                //制令单退料时，将退料数量记录在物料领用表，并返回到库存上
                                QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                                MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                                if (mesMaterielOccupy != null) {
                                    BigDecimal originalNum = new BigDecimal(mesMaterielOccupy.getWithdrawNum());//原有的数量
                                    BigDecimal withdrawNum = originalNum.add(inputNum);//新的退料数量 = 原有数量 + 退料数量
                                    //退料更新库存操作
                                    /*QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                                    queryWrapper.eq("materiel_code", mCode);
                                    MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);*/
                                    MesStockManage stockManage = mesStockManageService.queryByMcodeAndClient(mCode,mesOrderProduce.getClient());
                                    System.out.println("265退料："+mCode+"  客戶："+mesOrderProduce.getClient()+" stockManage:"+stockManage);
                                    if (stockManage != null) {
                                        BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                        BigDecimal stockNewNum = stockNum.add(inputNum);//新库存数量 = 库存数量 + 退料数量
                                        stockManage.setStockNum(stockNewNum.toString());
                                        mesStockManageService.updateById(stockManage);
                                        //更新领料表的退料数量
                                        mesMaterielOccupy.setWithdrawNum(withdrawNum.toString());
                                        mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                        //更新制令单Bom表的退料数量
                                        commandbillPitem.setWithdrawNum(withdrawNum.toString());
                                        produceClient.editComitem(commandbillPitem);
                                    } else {
                                        return Result.error("没有找到库存数据！请检查！");
                                    }

                                } else {
                                    return Result.error("没有找到物料领用信息！请检查！");
                                }
                            } else {
                                return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                            }
                        }
                        BeanUtils.copyProperties(commandbillPitem, mesCertificateItem);
                        mesCertificateItem.setId(null);//主键设置为null
                        mesCertificateItem.setCreateBy(null);//创建人设置为null
                        mesCertificateItem.setCreateTime(null);//创建时间设置为null
                        mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                        mesCertificateItemService.save(mesCertificateItem);
                        return Result.ok(mesCertificateItem);
                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("制令单退料时移动编号不等于265！请检查");
                }
            } else {
                if (certificateItem.getMobileCode().equals(mobileCode)) {

                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    BigDecimal oldNum = new BigDecimal(certificateItem.getInputNum());//原有数量
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    if (commandbillPitem != null) {
                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                        BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum()); //退料数量
                        BigDecimal certificateNum = oldNum.add(inputNum);//新的凭证数量 = 已有数量+退料数量
                        BigDecimal remainNum = deliveryNum.subtract(certificateNum);//剩余数量 = 新的凭证数量 - 已发料数量
                        //如果退料总数量（新的凭证数量）大于已发料数量，则报错数量不符
                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                            return Result.error("数量不符!请检查！");
                        } else {
                            //退料操作
                            if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(commandbillPitem.getMaterielCode())) {
                                //通过订单id与物料料号，查询领料表信息
                                String orderId = commandbillPitem.getProorderId();//生产订单id
                                MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                String mCode = commandbillPitem.getMaterielCode();//物料料号
                                //制令单退料时，将退料数量记录在物料领用表，并返回到库存上
                                QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                                MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                                if (mesMaterielOccupy != null) {
                                    BigDecimal originalNum = new BigDecimal(mesMaterielOccupy.getWithdrawNum());//原有的数量
                                    BigDecimal withdrawNum = originalNum.add(inputNum);//新的退料数量 = 原有数量 + 退料数量
                                    //退料更新库存操作
                                    /*QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                                    queryWrapper.eq("materiel_code", mCode);
                                    MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);*/
                                    MesStockManage stockManage = mesStockManageService.queryByMcodeAndClient(mCode,mesOrderProduce.getClient());
                                    System.out.println("退料："+mCode+"  客戶："+mesOrderProduce.getClient()+" stockManage:"+stockManage);
                                    if (stockManage != null) {
                                        BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                        BigDecimal stockNewNum = stockNum.add(inputNum);//新库存数量 = 库存数量 + 退料数量
                                        stockManage.setStockNum(stockNewNum.toString());
                                        mesStockManageService.updateById(stockManage);
                                        //更新领料表的退料数量
                                        mesMaterielOccupy.setWithdrawNum(withdrawNum.toString());
                                        mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                        //更新制令单Bom表的退料数量
                                        commandbillPitem.setWithdrawNum(withdrawNum.toString());
                                        produceClient.editComitem(commandbillPitem);
                                    } else {
                                        return Result.error("没有找到库存数据！请检查！");
                                    }

                                } else {
                                    return Result.error("没有找到物料领用信息！请检查！");
                                }
                            } else {
                                return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                            }
                        }
                        certificateItem.setInputNum(certificateNum.toString());
                        mesCertificateItemService.updateById(certificateItem);
                        return Result.ok(certificateItem);
                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("制令单退料时移动编号不等于265！请检查");
                }
            }
        } else {
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
    }

    /**
     * app制令单转产
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app制令单转产")
    @ApiOperation(value = "物料凭证项目-app制令单转产", notes = "物料凭证项目-app制令单转产")
    @PostMapping(value = "/addChangeProduce")
    public Result<?> addChangeProduce(@RequestBody MesCertificateItem mesCertificateItem) {
        String perkId = mesCertificateItem.getPerkId();
        String mobileType = mesCertificateItem.getMobileType();
        String materielCode = mesCertificateItem.getMaterielCode();
        //凭证抬头和业务编码不为空进入查询
        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            //物料料号不为空，查询物料对应的物料凭证子表
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType).eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }
            MesCertificateItem certificateItem = mesCertificateItemService.getOne(wrapper);
            String mobileCode = "266";
            //判断凭证项目有没有数据
            if (certificateItem == null) {
                //266 制令单转产
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    //录入数量
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    String mCode = commandbillPitem.getMaterielCode();//物料料号
                    //通过转产制令单号和物料料号，通过远程调用，获取转产制令单Bom的数据
                    String changeCode = mesCertificateItem.getQuery5();//转产制令单号
                    MesCommandbillPitem pitem = produceClient.getPitemByCode(changeCode, mCode);
                    if (pitem != null) {
                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
                        BigDecimal consumeNum = new BigDecimal(commandbillPitem.getConsumeNum());//已消耗数量
                        BigDecimal withdrawNum = new BigDecimal(commandbillPitem.getWithdrawNum());//已退料数量
                        if (StringUtils.isBlank(commandbillPitem.getTransformNum())) {
                            commandbillPitem.setTransformNum("0");
                        }
                        BigDecimal transformNum = new BigDecimal(commandbillPitem.getTransformNum());//已转产数量
                        BigDecimal adviceNum = deliveryNum.subtract(consumeNum.add(withdrawNum).add(transformNum));//建议转产数量
                        BigDecimal realNum = new BigDecimal(mesCertificateItem.getInputNum());//实际转产数量
                        if (realNum.compareTo(adviceNum) == 1) {
                            return Result.error("数量不符！请检查！");
                        } else {
                            //进入转产操作
                            if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(pitem.getProorderId()) && StringUtils.isNotBlank(mCode)) {
                                //通过订单id与物料料号，查询领料表信息
                                String orderId = pitem.getProorderId();//转产制令单关联的生产订单id
                                String produceId = commandbillPitem.getProorderId();//原有制令单关联的生产订单id
                                if (!produceId.equals(orderId)) {
                                    QueryWrapper<MesMaterielOccupy> occupyWrapper = new QueryWrapper<>();
                                    occupyWrapper.eq("order_id", produceId).eq("materiel_code", mCode);
                                    MesMaterielOccupy materielOccupy = mesMaterielOccupyService.getOne(occupyWrapper);
                                    //领料记录是空的则新增领料记录
                                    if (materielOccupy == null) {
                                        materielOccupy = new MesMaterielOccupy();
                                        materielOccupy.setOrderId(orderId);
                                        MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                        if (mesOrderProduce != null) {
                                            materielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                            materielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                        }
                                        materielOccupy.setMaterielCode(mCode);
                                        materielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                        materielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                        if (commandbillPitem != null) {
                                            materielOccupy.setOccupyNum(commandbillPitem.getRequireNum());
                                        }
                                        materielOccupy.setUnusedNum("0");
                                        materielOccupy.setWithdrawNum("0");
                                        materielOccupy.setTransformNum("0");
                                        mesMaterielOccupyService.save(materielOccupy);
                                    }
                                    if (materielOccupy != null) {
                                        BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                        //更新领料表的转产数量
                                        materielOccupy.setTransformNum(transNewnum.toString());
                                        mesMaterielOccupyService.updateById(materielOccupy);
                                        //更新原有制令单Bom表的转产数量
                                        commandbillPitem.setTransformNum(transNewnum.toString());
                                        produceClient.editComitem(commandbillPitem);
                                    } else {
                                        return Result.error("没有找到原有制令单的物料领用信息！请检查！");
                                    }

                                    //制令单转产时，将原有制令单的转产数量，加到转产制令单的物料领用单的发料数量上
                                    QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                    materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                                    MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                                    //领料记录是空的则新增领料记录
                                    if (mesMaterielOccupy == null) {
                                        mesMaterielOccupy = new MesMaterielOccupy();
                                        mesMaterielOccupy.setOrderId(orderId);
                                        MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                        if (mesOrderProduce != null) {
                                            mesMaterielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                            mesMaterielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                        }
                                        mesMaterielOccupy.setMaterielCode(mCode);
                                        mesMaterielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                        mesMaterielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                        if (pitem != null) {
                                            mesMaterielOccupy.setOccupyNum(pitem.getRequireNum());
                                        }
                                        mesMaterielOccupy.setUnusedNum("0");
                                        mesMaterielOccupy.setWithdrawNum("0");
                                        mesMaterielOccupy.setTransformNum("0");
                                        mesMaterielOccupyService.save(mesMaterielOccupy);
                                    }
                                    if (mesMaterielOccupy != null) {
                                        BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的发料数量
                                        BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有的发料数量 + 转产数量
                                        //更新领料表的发料数量
                                        mesMaterielOccupy.setSendNum(deliveryNewnum.toString());
                                        mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                        //更新转产制令单Bom表的发料数量
                                        pitem.setDeliveryNum(deliveryNewnum.toString());
                                        produceClient.editComitem(pitem);
                                    } else {
                                        return Result.error("没有找到转产制令单的物料领用信息！请检查！");
                                    }
                                } else {
                                    BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                    commandbillPitem.setTransformNum(transNewnum.toString());
                                    produceClient.editComitem(commandbillPitem);

                                    BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的数量
                                    BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有数量 + 转产数量
                                    pitem.setDeliveryNum(deliveryNewnum.toString());
                                    produceClient.editComitem(pitem);
                                }
                            } else {
                                return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                            }
                            mesCertificateItem.setId(null);
                            mesCertificateItem.setInputNum(realNum.toString());//退料数量
                            BeanUtils.copyProperties(commandbillPitem, mesCertificateItem);
                            mesCertificateItem.setId(null);//主键设置为null
                            mesCertificateItem.setCreateBy(null);//创建人设置为null
                            mesCertificateItem.setCreateTime(null);//创建时间设置为null
                            mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                            mesCertificateItem.setFactoryCode("转产");//类型
                            mesCertificateItem.setFactoryName("原单号: " + commandbillPitem.getCommandbillCode()); //原制令单
                            mesCertificateItem.setStorageSite("转产单号: " + pitem.getCommandbillCode());//转产制令单号
                            mesCertificateItemService.save(mesCertificateItem);
                            return Result.ok("转产成功");
                        }
                    } else {
                        return Result.error("没有找到转产制令单BOM的数据！请检查！");
                    }
                } else {
                    return Result.error("制令单转产时移动编号不等于266！请检查");
                }
            } else {
                if (certificateItem.getMobileCode().equals(mobileCode)) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    String mCode = commandbillPitem.getMaterielCode();//物料料号
                    //通过转产制令单号和物料料号，通过远程调用，获取转产制令单Bom的数据
                    String changeCode = mesCertificateItem.getQuery5();//转产制令单号
                    MesCommandbillPitem pitem = produceClient.getPitemByCode(changeCode, mCode);
                    if (pitem != null) {
                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
                        BigDecimal consumeNum = new BigDecimal(commandbillPitem.getConsumeNum());//已消耗数量
                        BigDecimal withdrawNum = new BigDecimal(commandbillPitem.getWithdrawNum());//已退料料数量
                        if (StringUtils.isBlank(commandbillPitem.getTransformNum())) {
                            commandbillPitem.setTransformNum("0");
                        }
                        BigDecimal transformNum = new BigDecimal(commandbillPitem.getTransformNum());//已转产数量
                        BigDecimal adviceNum = deliveryNum.subtract(consumeNum.add(withdrawNum).add(transformNum));//建议转产数量
                        BigDecimal realNum = new BigDecimal(mesCertificateItem.getInputNum());//实际转产数量
                        if (realNum.compareTo(adviceNum) == 1) {
                            return Result.error("数量不符！请检查！");
                        } else {
                            //进入转产操作
                            if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(pitem.getProorderId()) && StringUtils.isNotBlank(mCode)) {
                                //通过订单id与物料料号，查询领料表信息
                                String orderId = pitem.getProorderId();//转产制令单管理的生产订单id
                                String produceId = commandbillPitem.getProorderId();//原有制令单关联的生产订单id
                                if (!produceId.equals(orderId)) {
                                    QueryWrapper<MesMaterielOccupy> occupyWrapper = new QueryWrapper<>();
                                    occupyWrapper.eq("order_id", produceId).eq("materiel_code", mCode);
                                    MesMaterielOccupy materielOccupy = mesMaterielOccupyService.getOne(occupyWrapper);
                                    //领料记录是空的则新增领料记录
                                    if (materielOccupy == null) {
                                        materielOccupy = new MesMaterielOccupy();
                                        materielOccupy.setOrderId(orderId);
                                        MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                        if (mesOrderProduce != null) {
                                            materielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                            materielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                        }
                                        materielOccupy.setMaterielCode(mCode);
                                        materielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                        materielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                        if (commandbillPitem != null) {
                                            materielOccupy.setOccupyNum(commandbillPitem.getRequireNum());
                                        }
                                        materielOccupy.setUnusedNum("0");
                                        materielOccupy.setWithdrawNum("0");
                                        materielOccupy.setTransformNum("0");
                                        mesMaterielOccupyService.save(materielOccupy);
                                    }
                                    if (materielOccupy != null) {
                                        BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                        //更新领料表的转产数量
                                        materielOccupy.setTransformNum(transNewnum.toString());
                                        mesMaterielOccupyService.updateById(materielOccupy);
                                        //更新原有制令单Bom表的转产数量
                                        commandbillPitem.setTransformNum(transNewnum.toString());
                                        produceClient.editComitem(commandbillPitem);
                                    } else {
                                        return Result.error("没有找到原有制令单的物料领用信息！请检查！");
                                    }

                                    QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                    materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                                    MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);

                                    //领料记录是空的则新增领料记录
                                    if (mesMaterielOccupy == null) {
                                        mesMaterielOccupy = new MesMaterielOccupy();
                                        mesMaterielOccupy.setOrderId(orderId);
                                        MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                        if (mesOrderProduce != null) {
                                            mesMaterielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                            mesMaterielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                        }
                                        mesMaterielOccupy.setMaterielCode(mCode);
                                        mesMaterielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                        mesMaterielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                        if (pitem != null) {
                                            mesMaterielOccupy.setOccupyNum(pitem.getRequireNum());
                                        }
                                        mesMaterielOccupy.setUnusedNum("0");
                                        mesMaterielOccupy.setWithdrawNum("0");
                                        mesMaterielOccupy.setTransformNum("0");
                                        mesMaterielOccupyService.save(mesMaterielOccupy);
                                    }
                                    if (mesMaterielOccupy != null) {
                                        BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的数量
                                        BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有数量 + 转产数量
                                        //更新领料表的退料数量
                                        mesMaterielOccupy.setSendNum(deliveryNewnum.toString());
                                        mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                        //更新转产制令单Bom表的发料数量
                                        pitem.setDeliveryNum(deliveryNewnum.toString());
                                        produceClient.editComitem(pitem);
                                    } else {
                                        return Result.error("没有找到转产制令单的物料领用信息！请检查！");
                                    }
                                } else {
                                    BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                    commandbillPitem.setTransformNum(transNewnum.toString());
                                    produceClient.editComitem(commandbillPitem);

                                    BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的数量
                                    BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有数量 + 转产数量
                                    pitem.setDeliveryNum(deliveryNewnum.toString());
                                    produceClient.editComitem(pitem);
                                }
                            } else {
                                return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                            }
                            BigDecimal cetificateOldNum = new BigDecimal(certificateItem.getInputNum());//原有数量
                            BigDecimal cetificateNum = cetificateOldNum.add(realNum);//转产数量
                            certificateItem.setInputNum(cetificateNum.toString());//新的转产数量 = 原有数量+转产数量
                            mesCertificateItemService.updateById(certificateItem);
                            return Result.ok("转产成功");
                        }
                    } else {
                        return Result.error("没有找到转产制令单BOM的数据！请检查！");
                    }
                } else {
                    return Result.error("制令单转产时移动编号不等于266！请检查");
                }
            }
        } else {
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
    }

    /**
     * app制令单批量退料
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app制令单批量退料")
    @ApiOperation(value = "物料凭证项目-app制令单批量退料", notes = "物料凭证项目-app制令单批量退料")
    @PostMapping(value = "/wholeReturnMateriel")
    public Result<?> wholeReturnMateriel(@RequestBody MesCertificateItem mesCertificateItem) {
        String perkId = mesCertificateItem.getPerkId();
        String mobileType = mesCertificateItem.getMobileType();
        String materielCode = mesCertificateItem.getMaterielCode();
        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType).eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }
            List<MesCertificateItem> certificateItemList = mesCertificateItemService.list(wrapper);
            String mobileCode = "267";
            if (certificateItemList.size() == 0) {
                //267 制令单批量退料
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    List<MesCommandbillPitem> mesCommandbillPitemList = mesCertificateItem.getMesCommandbillPitemList();
                    if (mesCommandbillPitemList.size() != 0) {
                        for (MesCommandbillPitem commandbillPitem : mesCommandbillPitemList) {
                            BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
                            BigDecimal consumeNum = new BigDecimal(commandbillPitem.getConsumeNum());//已消耗数量
                            BigDecimal withdrawNum = new BigDecimal(commandbillPitem.getWithdrawNum());//已退料数量
                            BigDecimal realNum = new BigDecimal(commandbillPitem.getVirtualNum());//实际退料数量
                            BigDecimal withdrawNewNum = withdrawNum.add(realNum);//新退料数量 = 已退料数量+实际退料数量
                            BigDecimal adviceNum = deliveryNum.subtract(consumeNum);//建议退料数量
                            commandbillPitem.setAdviceNum(adviceNum.toString());
                            if (realNum.compareTo(adviceNum) == 1 || withdrawNewNum.compareTo(adviceNum) == 1) {
                                return Result.error("数量不符！请检查！");
                            } else {
                                //退料操作
                                if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(commandbillPitem.getMaterielCode())) {
                                    //通过订单id与物料料号，查询领料表信息
                                    String orderId = commandbillPitem.getProorderId();//生产订单id
                                    String mCode = commandbillPitem.getMaterielCode();//物料料号
                                    //制令单退料时，将退料数量记录在物料领用表，并返回到库存上
                                    QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                    materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                                    MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                                    if (mesMaterielOccupy != null) {
                                        BigDecimal originalNum = new BigDecimal(commandbillPitem.getWithdrawNum());//原有的数量
                                        BigDecimal withdrawNewnum = originalNum.add(realNum);//新的退料数量 = 原有数量 + 退料数量
                                        //退料更新库存操作
                                        QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                                        queryWrapper.eq("materiel_code", mCode);
                                        MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                                        if (stockManage != null) {
                                            BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                            BigDecimal stockNewNum = stockNum.add(realNum);//新库存数量 = 库存数量 + 退料数量
                                            stockManage.setStockNum(stockNewNum.toString());
                                            mesStockManageService.updateById(stockManage);
                                            //更新领料表的退料数量
                                            mesMaterielOccupy.setWithdrawNum(withdrawNewnum.toString());
                                            mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                            //更新制令单Bom表的退料数量
                                            commandbillPitem.setWithdrawNum(withdrawNewnum.toString());
                                            produceClient.editComitem(commandbillPitem);
                                        } else {
                                            return Result.error("没有找到库存数据！请检查！");
                                        }
                                    } else {
                                        return Result.error("没有找到物料领用信息！请检查！");
                                    }
                                } else {
                                    return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                                }
                                mesCertificateItem.setId(null);
                                mesCertificateItem.setInputNum(realNum.toString());//退料数量
                                BeanUtils.copyProperties(commandbillPitem, mesCertificateItem);
                                mesCertificateItem.setId(null);//主键设置为null
                                mesCertificateItem.setCreateBy(null);//创建人设置为null
                                mesCertificateItem.setCreateTime(null);//创建时间设置为null
                                mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                                mesCertificateItemService.save(mesCertificateItem);
                            }
                        }
                        return Result.ok("制令单批量退料成功");
                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查！");
                    }
                } else {
                    return Result.error("制令单批量退料时移动编号不等于267！请检查");
                }
            } else if (certificateItemList.size() >= 1) {
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    List<MesCommandbillPitem> mesCommandbillPitemList = mesCertificateItem.getMesCommandbillPitemList();
                    if (mesCommandbillPitemList.size() != 0) {
                        for (MesCommandbillPitem commandbillPitem : mesCommandbillPitemList) {
                            BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
                            BigDecimal consumeNum = new BigDecimal(commandbillPitem.getConsumeNum());//已消耗数量
                            BigDecimal withdrawNum = new BigDecimal(commandbillPitem.getWithdrawNum());//已退料数量
                            BigDecimal realNum = new BigDecimal(commandbillPitem.getVirtualNum());//实际退料数量
                            BigDecimal withdrawNewNum = withdrawNum.add(realNum);//新退料数量 = 已退料数量+实际退料数量
                            BigDecimal adviceNum = deliveryNum.subtract(consumeNum);//建议退料数量
                            commandbillPitem.setAdviceNum(adviceNum.toString());
                            if (realNum.compareTo(adviceNum) == 1 || withdrawNewNum.compareTo(adviceNum) == 1) {
                                return Result.error("数量不符！请检查！");
                            } else {
                                //退料操作
                                if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(commandbillPitem.getMaterielCode())) {
                                    //通过订单id与物料料号，查询领料表信息
                                    String orderId = commandbillPitem.getProorderId();//生产订单id
                                    String mCode = commandbillPitem.getMaterielCode();//物料料号
                                    //制令单退料时，将退料数量记录在物料领用表，并返回到库存上
                                    QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                    materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                                    MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                                    if (mesMaterielOccupy != null) {
                                        BigDecimal originalNum = new BigDecimal(commandbillPitem.getWithdrawNum());//原有的数量
                                        BigDecimal withdrawNewnum = originalNum.add(realNum);//新的退料数量 = 原有数量 + 退料数量
                                        //退料更新库存操作
                                        QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                                        queryWrapper.eq("materiel_code", mCode);
                                        MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                                        if (stockManage != null) {
                                            BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                            BigDecimal stockNewNum = stockNum.add(realNum);//新库存数量 = 库存数量 + 退料数量
                                            stockManage.setStockNum(stockNewNum.toString());
                                            mesStockManageService.updateById(stockManage);
                                            //更新领料表的退料数量
                                            mesMaterielOccupy.setWithdrawNum(withdrawNewnum.toString());
                                            mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                            //更新制令单Bom表的退料数量
                                            commandbillPitem.setWithdrawNum(withdrawNewnum.toString());//已退料数量
                                            commandbillPitem.setAdviceNum(adviceNum.toString());//建议退料数量
                                            produceClient.editComitem(commandbillPitem);
                                            //更新物料凭证数量
                                            QueryWrapper<MesCertificateItem> certificateWrapper = new QueryWrapper<>();
                                            certificateWrapper.eq("materiel_code", mCode).eq("perk_id", perkId).eq("mobile_code", "267");
                                            MesCertificateItem certificateItem = mesCertificateItemService.getOne(certificateWrapper);
                                            if (certificateItem != null) {
                                                BigDecimal certificateOldNum = new BigDecimal(certificateItem.getInputNum());
                                                BigDecimal certificateNum = certificateOldNum.add(realNum);
                                                certificateItem.setInputNum(certificateNum.toString());
                                                mesCertificateItemService.updateById(certificateItem);
                                            } else {
                                                return Result.error("没有找到物料凭证项目数据！请检查！");
                                            }
                                        } else {
                                            return Result.error("没有找到库存数据！请检查！");
                                        }
                                    } else {
                                        return Result.error("没有找到物料领用信息！请检查！");
                                    }
                                } else {
                                    return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                                }
                            }
                        }
                        return Result.ok("制令单批量退料成功");
                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查！");
                    }
                } else {
                    return Result.error("制令单批量退料时移动编号不等于267！请检查");
                }
            }
        } else {
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
        return Result.ok("制令单批量退料成功");
    }


    @AutoLog(value = "物料凭证项目-转产查询，根据旧单号和新单号查询凭证抬头信息")
    @ApiOperation(value = "物料凭证项目-转产查凭证抬头", notes = "物料凭证项目-转产查询，根据旧单号和新单号查询凭证抬头信息")
    @GetMapping(value = "/getChangeProduce")
    public Result<?> getChangeProduce(@RequestParam(name = "oldCode", required = true) String oldCode, @RequestParam(name = "nowCode", required = true) String nowCode) {
        List<MesCertificatePerk> changeProduces = mesCertificatePerkService.getChangeProduce("原单号: " + oldCode, nowCode);
        if (changeProduces.size() > 0) {
            return Result.OK(changeProduces.get(0));
        } else {
            return Result.OK(null);
        }
    }

    /**
     * app制令单批量转产
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app制令单批量转产")
    @ApiOperation(value = "物料凭证项目-app制令单批量转产", notes = "物料凭证项目-app制令单批量转产")
    @PostMapping(value = "/wholeChangeProduce")
    public Result<?> wholeChangeProduce(@RequestBody MesCertificateItem mesCertificateItem) {
        boolean mark = mesCertificateItemService.wholeChangeProduce(mesCertificateItem);
        if (mark) {
            return Result.ok("制令单批量转产成功");
        } else {
            return Result.error("制令单批量转产失败");
        }
    }

    /**
     * app制令单扫描入库
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app制令单扫描入库")
    @ApiOperation(value = "物料凭证项目-app制令单扫描入库", notes = "物料凭证项目-app制令单扫描入库")
    @PostMapping(value = "/scanEnterWarehouse")
    public Result<?> scanEnterWarehouse(@RequestBody MesCertificateItem mesCertificateItem) {
        String perkId = mesCertificateItem.getPerkId();
        String mobileType = mesCertificateItem.getMobileType();
        //String materielCode = mesCertificateItem.getMaterielCode();
        if (StringUtils.isNotBlank(mesCertificateItem.getCommandId())) {
            /*MesCommandbillPitem item = produceClient.getItemByCommandIdAndType(mesCertificateItem.getCommandId(), "PCB");
            if (com.epms.util.ObjectHelper.isNotEmpty(item) && StringUtils.isNotBlank(item.getMaterielCode())) {
                materielCode = item.getMaterielCode();//物料料号
            }*/
            MesCommandbillInfo mesCommandbillInfo = produceClient.getById(mesCertificateItem.getCommandId());
            if (com.epms.util.ObjectHelper.isNotEmpty(mesCommandbillInfo)) {
                mesCertificateItem.setMaterielCode(mesCommandbillInfo.getMechanismCode());//添加凭证抬头时将制令单机种料号放入物料编号
                if (StringUtils.isBlank(mesCertificateItem.getReserveCode())) {
                    mesCertificateItem.setReserveCode(mesCommandbillInfo.getProduceId());
                }
            }
        }
        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(mesCertificateItem.getMaterielCode())) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType).eq("materiel_code", mesCertificateItem.getMaterielCode());
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }
            MesCertificateItem certificateItem = mesCertificateItemService.getOne(wrapper);
            String mobileCode = "201";
            if (certificateItem == null) {
                //201 制令单扫描入库
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    //通过预留编号（生产订单id），获取生产订单主表的相应数据
                    MesOrderProduce produce = transactionClient.queryMesProduceById(mesCertificateItem.getReserveCode());
                    if (produce != null) {

                        BeanUtils.copyProperties(produce, mesCertificateItem);
                        mesCertificateItem.setId(null);//主键设置为null
                        mesCertificateItem.setCreateBy(null);//创建人设置为null
                        mesCertificateItem.setCreateTime(null);//创建时间设置为null
                        mesCertificateItem.setInputNum("0");
                        mesCertificateItem.setMaterielGauge(produce.getGauge());//物料规格
                        mesCertificateItem.setInputUnit(produce.getUnit());// 单位
                        //mesCertificateItem.setMaterielCode(materielCode);//物料编号
                        mesCertificateItemService.save(mesCertificateItem);
                        return Result.ok(mesCertificateItem);
                    } else {
                        return Result.error("没有找到生产订单的数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("制令单扫描入库时移动编号不等于201！请检查");
                }
            } else {
                if (certificateItem.getMobileCode().equals(mobileCode)) {
                    return Result.ok(certificateItem);
                } else {
                    return Result.error("制令单扫描入库时移动编号不等于201！请检查");
                }
            }
        } else {
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
    }

    /**
     * app发货
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app发货")
    @ApiOperation(value = "物料凭证项目-app发货", notes = "物料凭证项目-app发货")
    @PostMapping(value = "/addSendProduct")
    public Result<?> addSendProduct(@RequestBody MesCertificateItem mesCertificateItem) {
        String perkId = mesCertificateItem.getPerkId();
        String mobileType = mesCertificateItem.getMobileType();
        String materielCode = mesCertificateItem.getMaterielCode();
        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType).eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }
            MesCertificateItem certificateItem = mesCertificateItemService.getOne(wrapper);
            String mobileCode = "601";
            if (certificateItem == null) {
                //601 发货
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    MesSaleItem mesSaleItem = transactionClient.queryMesSaleItemById(mesCertificateItem.getReserveCode());
                    if (mesSaleItem != null) {
                        BigDecimal undeliveryNum = new BigDecimal(mesSaleItem.getUndeliveryNum());//未发货数量
                        BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//发货数量
                        BigDecimal remainNum = undeliveryNum.subtract(inputNum);//剩余数量 = 未发货数量 - 发货数量
                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                            return Result.error("数量不符！请检查！");
                        } else {
                            MesOrderSale mesOrderSale = transactionClient.queryMesSaleOrderById(mesSaleItem.getSaleorderId());
                            if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                                mesSaleItem.setState("完成");//全部发货完成，改变销售订单状态为完成
                                if (mesOrderSale != null) {
                                    mesOrderSale.setState("完成");
                                    transactionClient.editSaleOrder(mesOrderSale);
                                }
                            }
                            mesSaleItem.setUndeliveryNum(remainNum.toString());
                            transactionClient.editSaleItem(mesSaleItem);

                            /*QueryWrapper<MesStockManage> stockWrapper = new QueryWrapper<>();
                            stockWrapper.eq("materiel_code", mesSaleItem.getMaterielCode());
                            MesStockManage stockManage = mesStockManageService.getOne(stockWrapper);*/
                            MesStockManage stockManage = mesStockManageService.queryByMcodeAndClient(mesSaleItem.getMaterielCode(), mesOrderSale.getSaleName());
                            if (stockManage != null) {
                                BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                BigDecimal newStockNum = stockNum.subtract(inputNum);
                                if (newStockNum.compareTo(BigDecimal.ZERO) == -1) {
                                    return Result.error("" + mesSaleItem.getMaterielName() + " 的库存数量不足！无法发货！");
                                } else {
                                    stockManage.setStockNum(newStockNum.toString());
                                    mesStockManageService.updateById(stockManage);
                                    if (StringUtils.isNotBlank(stockManage.getMinimum())) {
                                        BigDecimal minimum = new BigDecimal(stockManage.getMinimum());
                                        if (newStockNum.compareTo(minimum) < 1) {
                                            // 获取登录用户信息
                                            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                                            //测试时，向当前登录用户发送消息提醒；正式上线后，需要向采购人员（溢哲渝设定）发送库存临界点警告
                                            systemClient.sendMessage(sysUser.getUsername(), stockManage.getMaterielName());
                                            systemClient.sendMessage(mesSaleItem.getCreateBy(), stockManage.getMaterielName());
                                        }
                                    }
                                }
                            } else {
                                return Result.error("找不到【" + mesOrderSale.getSaleName() + "】 " + mesSaleItem.getMaterielName() + " 的库存数据。请检查库存管理中是否存在【" + mesOrderSale.getSaleName() + "】的区位编码！");
                            }
                        }
                        mesCertificateItem.setMobileType("发货");
                        BeanUtils.copyProperties(mesSaleItem, mesCertificateItem);
                        mesCertificateItem.setId(null);//主键设置为null
                        mesCertificateItem.setCreateBy(null);//创建人设置为null
                        mesCertificateItem.setCreateTime(null);//创建时间设置为null
                        mesCertificateItem.setInputUnit(mesSaleItem.getUnit());
                        mesCertificateItemService.save(mesCertificateItem);
                        //发货完成以后 插入出货流水记录,批号交易记录
                        addOutWaterRecord(mesCertificateItem, inputNum + "");

                        return Result.ok(mesCertificateItem);
                    } else {
                        return Result.error("没有找到销售订单子表数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("发货时移动编号不等于601！请检查");
                }
            } else {
                if (certificateItem.getMobileCode().equals(mobileCode)) {
                    MesSaleItem mesSaleItem = transactionClient.queryMesSaleItemById(mesCertificateItem.getReserveCode());
                    if (mesSaleItem != null) {
                        BigDecimal oldNum = new BigDecimal(certificateItem.getInputNum());//已有数量
                        BigDecimal undeliveryNum = new BigDecimal(mesSaleItem.getUndeliveryNum());//未发货数量
                        BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//发货数量
                        BigDecimal remainNum = undeliveryNum.subtract(inputNum);//剩余数量 = 未发货数量 - 发货数量
                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                            return Result.error("发货数量与未发货数量不符！请检查！");
                        } else {
                            MesOrderSale mesOrderSale = transactionClient.queryMesSaleOrderById(mesSaleItem.getSaleorderId());
                            /*QueryWrapper<MesStockManage> stockWrapper = new QueryWrapper<>();
                            stockWrapper.eq("materiel_code", mesSaleItem.getMaterielCode());
                            MesStockManage stockManage = mesStockManageService.getOne(stockWrapper);*/
                            MesStockManage stockManage = mesStockManageService.queryByMcodeAndClient(mesSaleItem.getMaterielCode(), mesOrderSale.getSaleName());
                            if (stockManage != null) {
                                BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());//原有的库存数量
                                BigDecimal newStockNum = stockNum.subtract(inputNum);//新的库存数量 = 原有的库存数量 - 发货数量
                                if (newStockNum.compareTo(BigDecimal.ZERO) == -1) {
                                    return Result.error("" + mesSaleItem.getMaterielName() + " 的库存数量不足！无法发货！");
                                } else {
                                    stockManage.setStockNum(newStockNum + "");
                                    mesStockManageService.updateById(stockManage);
                                    mesSaleItem.setUndeliveryNum(remainNum.toString());
                                    if (StringUtils.isNotBlank(stockManage.getMinimum())) {
                                        BigDecimal minimum = new BigDecimal(stockManage.getMinimum());//库存临界点
                                        //如果库存到达库存临界点，则提醒用户及时采购
                                        if (newStockNum.compareTo(minimum) < 1) {
                                            // 获取登录用户信息
                                            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                                            //测试时，向当前登录用户发送消息提醒；正式上线后，需要向采购人员（溢哲渝设定）发送库存临界点警告
                                            systemClient.sendMessage(sysUser.getUsername(), stockManage.getMaterielName());
                                            systemClient.sendMessage(mesSaleItem.getCreateBy(), stockManage.getMaterielName());
                                        }
                                    }
                                }
                            } else {
                                return Result.error("找不到【" + mesOrderSale.getSaleName() + "】 " + mesSaleItem.getMaterielName() + " 的库存数据。请检查库存管理中是否存在【" + mesOrderSale.getSaleName() + "】的区位编码！");
                            }

                            BigDecimal inputNumNew = oldNum.add(inputNum);
                            if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                                mesSaleItem.setState("完成");//全部发货完成，改变销售订单状态为完成
                                if (mesOrderSale != null) {
                                    mesOrderSale.setState("完成");
                                    transactionClient.editSaleOrder(mesOrderSale);
                                }
                                certificateItem.setInputNum(inputNumNew.toString());
                            }
                            transactionClient.editSaleItem(mesSaleItem);
                            certificateItem.setInputNum(inputNumNew.toString());
                        }
                        mesCertificateItemService.updateById(certificateItem);
                        //发货完成以后 插入出货流水记录，批号交易记录
                        addOutWaterRecord(mesCertificateItem, inputNum + "");

                        return Result.ok(certificateItem);
                    } else {
                        return Result.error("没有找到销售订单子表数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("发货时移动编号不等于601！请检查");
                }
            }
        } else {
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
    }

    /**
     * app退货
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app退货")
    @ApiOperation(value = "物料凭证项目-app退货", notes = "物料凭证项目-app退货")
    @PostMapping(value = "/addReturnProduct")
    public Result<?> addReturnProduct(@RequestBody MesCertificateItem mesCertificateItem) {
        String perkId = mesCertificateItem.getPerkId();
        String mobileType = mesCertificateItem.getMobileType();
        String materielCode = mesCertificateItem.getMaterielCode();
        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType).eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }
            MesCertificateItem certificateItem = mesCertificateItemService.getOne(wrapper);
            String mobileCode = "602";
            if (certificateItem == null) {
                //602 退货
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    MesSaleItem mesSaleItem = transactionClient.queryMesSaleItemById(mesCertificateItem.getReserveCode());
                    if (mesSaleItem != null) {
                        BigDecimal orderNum = new BigDecimal(mesSaleItem.getOrderNum());//订单数量
                        BigDecimal undeliveryNum = new BigDecimal(mesSaleItem.getUndeliveryNum());//未发货数量
                        BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//退货数量
                        BigDecimal newNum = undeliveryNum.add(inputNum);//新的未发货数量 = 未发货数量 + 退货数量
                        BigDecimal remainNum = orderNum.subtract(inputNum);//剩余数量 = 订单数量 - 退货数量
                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                            return Result.error("数量不符！请检查！");
                        } else if (newNum.compareTo(orderNum) == 1) {
                            return Result.error("数量不符！请检查！");
                        } else {
                            mesSaleItem.setUndeliveryNum(newNum + "");
                            transactionClient.editSaleItem(mesSaleItem);
                        }
                        mesCertificateItem.setMobileType("退货");
                        BeanUtils.copyProperties(mesSaleItem, mesCertificateItem);
                        mesCertificateItem.setId(null);//主键设置为null
                        mesCertificateItem.setCreateBy(null);//创建人设置为null
                        mesCertificateItem.setCreateTime(null);//创建时间设置为null
                        mesCertificateItem.setInputUnit(mesSaleItem.getUnit());
                        mesCertificateItemService.save(mesCertificateItem);
                        return Result.ok(mesCertificateItem);
                    } else {
                        return Result.error("没有找到销售订单子表数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("退货时移动编号不等于602！请检查");
                }
            } else {
                if (certificateItem.getMobileCode().equals(mobileCode)) {
                    MesSaleItem mesSaleItem = transactionClient.queryMesSaleItemById(mesCertificateItem.getReserveCode());
                    if (mesSaleItem != null) {
                        BigDecimal orderNum = new BigDecimal(mesSaleItem.getOrderNum());//订单数量
                        BigDecimal oldNum = new BigDecimal(certificateItem.getInputNum());//已有数量
                        BigDecimal undeliveryNum = new BigDecimal(mesSaleItem.getUndeliveryNum());//未发货数量
                        BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//退货数量
                        BigDecimal newNum = undeliveryNum.add(inputNum);
                        BigDecimal remainNum = orderNum.subtract(inputNum);
                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                            return Result.error("数量不符！请检查！");
                        } else if (newNum.compareTo(orderNum) == 1) {
                            return Result.error("数量不符！请检查！");
                        } else {
                            BigDecimal newInputNum = oldNum.add(inputNum);
                            certificateItem.setInputNum(newInputNum.toString());
                            mesSaleItem.setUndeliveryNum(newNum.toString());
                            transactionClient.editSaleItem(mesSaleItem);
                        }
                        mesCertificateItemService.updateById(certificateItem);
                        return Result.ok(certificateItem);
                    } else {
                        return Result.error("没有找到销售订单子表数据！请检查预留编号是否正确！");
                    }
                } else {
                    return Result.error("退货时移动编号不等于602！请检查");
                }
            }
        } else {
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
    }

    /**
     * app扫描发货
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app扫描发货")
    @ApiOperation(value = "物料凭证项目-app扫描发货", notes = "物料凭证项目-app扫描发货")
    @PostMapping(value = "/scanSendProduct")
    public Result<?> scanSendProduct(@RequestBody MesCertificateItem mesCertificateItem) {
        String perkId = mesCertificateItem.getPerkId();
        String mobileType = mesCertificateItem.getMobileType();
        String materielCode = mesCertificateItem.getMaterielCode();
        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType).eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }
            MesCertificateItem certificateItem = mesCertificateItemService.getOne(wrapper);
            String mobileCode = "603";
            if (certificateItem == null) {
                //603 扫描发货
                if (mesCertificateItem.getMobileCode().equals(mobileCode)) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    MesSaleItem mesSaleItem = transactionClient.queryMesSaleItemById(mesCertificateItem.getReserveCode());
                    if (mesSaleItem != null) {
                        mesCertificateItem.setMobileType("扫描发货");
                        BeanUtils.copyProperties(mesSaleItem, mesCertificateItem);
                        mesCertificateItem.setId(null);//主键设置为null
                        mesCertificateItem.setCreateBy(null);//创建人设置为null
                        mesCertificateItem.setCreateTime(null);//创建时间设置为null
                        mesCertificateItem.setInputUnit(mesSaleItem.getUnit());
                        mesCertificateItemService.save(mesCertificateItem);
                        return Result.ok(mesCertificateItem);
                    } else {
                        return Result.error("没有找到销售订单子表数据！请检查！");
                    }
                } else {
                    return Result.error("扫描发货时移动编号不等于603！请检查");
                }
            } else {

                if (certificateItem.getMobileCode().equals(mobileCode)) {
                    return Result.ok(certificateItem);
                } else {
                    return Result.error("扫描发货时移动编号不等于603！请检查");
                }
            }
        } else {
            return Result.error("没有找到凭证抬头ID和移动类型！请检查");
        }
    }


    /**
     * 添加
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-app添加")
    @ApiOperation(value = "物料凭证项目-app添加", notes = "物料凭证项目-app添加")
    @PostMapping(value = "/addMesCertificateItem")
    public Result<?> addMesCertificateItem(@RequestBody MesCertificateItem mesCertificateItem) {
        String perkId = mesCertificateItem.getPerkId();
        String mobileType = mesCertificateItem.getMobileType();
        String materielCode = mesCertificateItem.getMaterielCode();
        if (StringUtils.isNotBlank(perkId) && StringUtils.isNotBlank(mobileType)) {
            QueryWrapper<MesCertificateItem> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielCode)) {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType).eq("materiel_code", materielCode);
            } else {
                wrapper.eq("perk_id", perkId).eq("mobile_type", mobileType);
            }
            List<MesCertificateItem> certificateItemList = mesCertificateItemService.list(wrapper);
            if (certificateItemList.size() != 0 && certificateItemList.size() == 1) {
                MesCertificateItem certificateItem1 = certificateItemList.get(0);
                System.err.println("找到了一条，进行编辑");
                //103 物料入库/收货
                if (certificateItem1.getMobileCode().equals("103")) {
                    MesCertificatePerk mesCertificatePerk = mesCertificatePerkService.getById(perkId);
                    mesCertificatePerk.setIfFinish("未完成");
                    mesCertificatePerk.setIfInput("未完成");
                    mesCertificatePerkService.updateById(mesCertificatePerk);
                    //通过预留编号（采购订单子表ID），获取采购订单子表的相应数据
                    MesPurchaseItem purchaseItem = transactionClient.queryMesPurchaseItemById(mesCertificateItem.getReserveCode());
                    //获取未收货数量，与收货数量做对比判断
                    BigDecimal unreceiveNum = new BigDecimal(purchaseItem.getUnreceiveNum());//未收货数量
                    if (StringUtils.isNotBlank(mesCertificateItem.getInputNum())) {
                        BigDecimal oldNum = new BigDecimal(certificateItem1.getInputNum());//已有数量
                        BigDecimal receiveNum = new BigDecimal(mesCertificateItem.getInputNum());//收货数量
                        BigDecimal remainNum = unreceiveNum.subtract(receiveNum);
                        BigDecimal inputNumNew = oldNum.add(receiveNum);
                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                            return Result.error("请检查收货数量是否正确！");
                        } else if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                            purchaseItem.setUnreceiveNum(remainNum.toString());
                            purchaseItem.setIfFinish("收货完成");
                            transactionClient.editPurchaseItem(purchaseItem);
                            certificateItem1.setInputNum(inputNumNew.toString());//入库数量
                            certificateItem1.setUnstorageNum(inputNumNew.toString());//未入库数量
                            //收货完成，向工作人员发送质检提醒；目前测试环境，向当前登录用户发送消息提醒，上线后修改
//                            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//                            systemClient.sendCheckMessage(sysUser.getUsername(), purchaseItem.getMaterielName(), inputNumNew.toString(), purchaseItem.getOrderUnit());
                            asyncUtils.asyncSend(purchaseItem);
                        } else {
                            purchaseItem.setUnreceiveNum(remainNum.toString());
                            transactionClient.editPurchaseItem(purchaseItem);
                            certificateItem1.setInputNum(inputNumNew.toString());//入库数量
                            certificateItem1.setUnstorageNum(inputNumNew.toString());//未入库数量
                        }
                    }
                }
                //261 制令单发料
                if (certificateItem1.getMobileCode().equals("261")) {
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                    if (StringUtils.isNotBlank(mesCertificateItem.getInputNum())) {
                        String orderId = commandbillPitem.getProorderId();//生产订单id
                        String mCode = commandbillPitem.getMaterielCode();//物料料号
                        String inputNum = mesCertificateItem.getInputNum();//发料数量
                        //制令单发料可以超发，先扣除领料单领取的数量；若超过领料数量，再从库存里扣除
                        QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                        materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                        MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                        if (mesMaterielOccupy != null) {
//							BigDecimal occupyNum = new BigDecimal(mesMaterielOccupy.getOccupyNum());//领用数量
                            BigDecimal unUsedNum = new BigDecimal(mesMaterielOccupy.getUnusedNum());//未使用数量
                            BigDecimal requireNum = new BigDecimal(inputNum);//发料数量
                            BigDecimal oldNum = new BigDecimal(certificateItem1.getInputNum());//物料凭证数量
                            if (unUsedNum.compareTo(requireNum) == -1) {//物料超发
                                System.err.println("你的思路是对的！");
                                BigDecimal usedStockNum = requireNum.subtract(unUsedNum);//超发的数量
                                QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("materiel_code", mCode);
                                MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                                if (stockManage == null) {
                                    return Result.error("查不到库存数据！请检查！");
                                } else {
                                    BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());//库存数量
                                    BigDecimal minimum = new BigDecimal(stockManage.getMinimum());//库存临界点
                                    BigDecimal remainNum = stockNum.subtract(usedStockNum);//剩余数量=库存数量-超发数量
                                    //如果库存数量小于0，则提示库存数量不足。反之，将剩余数量，更新到库存上
                                    if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                                        return Result.error("库存数量不足！请检查！");
                                    } else {
                                        stockManage.setStockNum(remainNum + "");//新的库存数量 = 剩余数量
                                        mesStockManageService.updateById(stockManage);
                                        //如果库存数量小于库存临界点，则给用户发送消息提醒
                                        if (remainNum.compareTo(minimum) < 1) {
                                            // 获取登录用户信息
                                            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                                            //测试时，向当前登录用户发送消息提醒；正式上线后，需要向采购人员（溢哲渝设定）发送库存临界点警告
                                            systemClient.sendMessage(sysUser.getUsername(), stockManage.getMaterielName());
                                        }
                                        BigDecimal num = deliveryNum.add(requireNum);//新的发料数量 = 原有数量+发料数量
                                        commandbillPitem.setDeliveryNum(num.toString());
                                        produceClient.editComitem(commandbillPitem);
                                        //更新领料表数据
                                        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                                        mesMaterielOccupy.setOccupyPerson(sysUser.getUsername());//发料人
                                        mesMaterielOccupy.setSendNum(num.toString());//发料数量
                                        mesMaterielOccupy.setOccupyTime(new Date());//发料时间
                                        mesMaterielOccupy.setUnusedNum("0");
                                        mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                        //更新物料凭证表数据
                                        BigDecimal newNum = oldNum.add(requireNum);
                                        certificateItem1.setInputNum(newNum.toString());//新物料凭证数量 = 旧数量 + 发料数量
                                    }
                                }
                            } else {//未超发
                                BigDecimal remainNum = unUsedNum.subtract(requireNum);//剩余数量 = 未领用数量-发料数量
                                BigDecimal num = deliveryNum.add(requireNum);//新的发料数量 = 原有数量+发料数量
                                commandbillPitem.setDeliveryNum(num.toString());
                                produceClient.editComitem(commandbillPitem);
                                //更新领料表数据
                                LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                                mesMaterielOccupy.setOccupyPerson(sysUser.getUsername());//发料人
                                mesMaterielOccupy.setSendNum(num.toString());//发料数量
                                mesMaterielOccupy.setOccupyTime(new Date());//发料时间
                                mesMaterielOccupy.setUnusedNum(remainNum.toString());//未使用数量
                                mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                //更新物料凭证表数据
                                BigDecimal newNum = oldNum.add(requireNum);
                                certificateItem1.setInputNum(newNum.toString());
                            }
                        } else {
                            return Result.error("领料数据为空！请检查！");
                        }
                    }
                }
                //263 制令单上料
                if (certificateItem1.getMobileCode().equals("263")) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    BigDecimal glazeNum = new BigDecimal(commandbillPitem.getUnglazeNum()); //原有数量
                    BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                    BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//上料数量
                    BigDecimal glazeNewNum = glazeNum.add(inputNum);//已上料数量=原有数量+上料数量
                    //如果已上料数量超过已发料数量，则提示错误数量不符
                    if (glazeNewNum.compareTo(deliveryNum) == 1) {
                        return Result.error("数量不符！请先检查！");
                    } else {
                        commandbillPitem.setUnglazeNum(glazeNewNum.toString());
                        produceClient.editComitem(commandbillPitem);

                        BigDecimal oldNum = new BigDecimal(certificateItem1.getInputNum());//凭证已有数量
                        BigDecimal certificateNum = oldNum.add(inputNum);//凭证新数量 = 凭证已有数量 + 上料数量
                        certificateItem1.setInputNum(certificateNum.toString());
                    }
                }
                // 262 制令单入库
                if (certificateItem1.getMobileCode().equals("262")) {
                    // 通过预留编号（生产订单ID），获取生产订单的相应数据
                    MesOrderProduce mesOrderProduce = transactionClient.queryMesProduceById(mesCertificateItem.getReserveCode());
                    BigDecimal receiveNum = new BigDecimal(mesCertificateItem.getInputNum());//入库数量
                    if (StringUtils.isNotBlank(mesCertificateItem.getCommandId())) {
                        MesCommandbillInfo mesCommandbillInfo = produceClient.getById(mesCertificateItem.getCommandId());
                        BigDecimal oldNum = new BigDecimal(certificateItem1.getInputNum());//已有数量
                        BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());
                        BigDecimal uninputNum = new BigDecimal(mesCommandbillInfo.getUninputNum());//未入库数量
                        BigDecimal remainNum = uninputNum.subtract(receiveNum);
                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                            return Result.error("请检查入库数量是否正确！");
                        } else if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                            mesCommandbillInfo.setUninputNum(remainNum.toString());
//							mesCommandbillInfo.setInputState("入库完成");
                            produceClient.editCommand(mesCommandbillInfo);
                            BigDecimal inputNumNew = oldNum.add(inputNum);
                            certificateItem1.setInputNum(inputNumNew.toString());
                        } else {
                            mesCommandbillInfo.setUninputNum(remainNum.toString());
                            produceClient.editCommand(mesCommandbillInfo);
                            BigDecimal inputNumNew = oldNum.add(inputNum);
                            certificateItem1.setInputNum(inputNumNew.toString());
                        }
                    }

                    QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("materiel_code", mesOrderProduce.getMaterielCode());
                    MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                    if (stockManage != null) {
                        BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                        BigDecimal newStock = stockNum.add(receiveNum);
                        stockManage.setStockNum(newStock.toString());
                        mesStockManageService.updateById(stockManage);
                    } else {
                        MesStockManage mesStockManage = new MesStockManage();
                        mesStockManage.setMaterielCode(mesOrderProduce.getMaterielCode());
                        mesStockManage.setMaterielName(mesOrderProduce.getMaterielName());
                        mesStockManage.setMaterielGague(mesOrderProduce.getGauge());
                        mesStockManage.setFactoryId(mesOrderProduce.getFactoryId());
                        mesStockManage.setFactoryCode(mesOrderProduce.getFactoryCode());
                        mesStockManage.setFactoryName(mesOrderProduce.getFactoryName());
                        mesStockManage.setStoreName(mesOrderProduce.getStorageSite());
                        mesStockManage.setUnit(mesOrderProduce.getUnit());
                        mesStockManage.setStockNum(receiveNum + "");
                        MesChiefdataMateriel mater = systemClient.queryByMcode(mesStockManage.getMaterielCode());
                        if (mater != null) {
                            mesStockManage.setQuery5(mater.getMaterielType());
                        }
                        mesStockManageService.save(mesStockManage);
                    }

                }
                //264 制令单扫描发料
                if (certificateItem1.getMobileCode().equals("264")) {
                    return Result.ok(certificateItem1);
                }
                //265 制令单退料  //判断是原材料还是不良品
                if (certificateItem1.getMobileCode().equals("265")) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    BigDecimal oldNum = new BigDecimal(certificateItem1.getInputNum());//原有数量
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                    BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum()); //退料数量
                    BigDecimal certificateNum = oldNum.add(inputNum);//新的凭证数量 = 已有数量+退料数量
                    BigDecimal remainNum = deliveryNum.subtract(certificateNum);//剩余数量 = 新的凭证数量 - 已发料数量
                    //如果退料总数量（新的凭证数量）大于已发料数量，则报错数量不符
                    if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                        return Result.error("数量不符!请检查！");
                    } else {
                        certificateItem1.setInputNum(certificateNum.toString());
                        //退料操作
                        if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(commandbillPitem.getMaterielCode())) {
                            //通过订单id与物料料号，查询领料表信息
                            String orderId = commandbillPitem.getProorderId();//生产订单id
                            MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                            String mCode = commandbillPitem.getMaterielCode();//物料料号
                            //制令单退料时，将退料数量记录在物料领用表，并返回到库存上
                            QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                            materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                            MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                            //领料记录是空的则新增领料记录
                            if (mesMaterielOccupy == null) {
                                mesMaterielOccupy = new MesMaterielOccupy();
                                mesMaterielOccupy.setOrderId(orderId);
                                if (mesOrderProduce != null) {
                                    mesMaterielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                    mesMaterielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                }
                                mesMaterielOccupy.setMaterielCode(mCode);
                                mesMaterielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                mesMaterielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                if (commandbillPitem != null) {
                                    mesMaterielOccupy.setOccupyNum(commandbillPitem.getRequireNum());
                                }
                                mesMaterielOccupy.setUnusedNum("0");
                                mesMaterielOccupy.setWithdrawNum("0");
                                mesMaterielOccupy.setTransformNum("0");
                                mesMaterielOccupyService.save(mesMaterielOccupy);
                            }

                            if (mesMaterielOccupy != null) {
                                BigDecimal originalNum = new BigDecimal(mesMaterielOccupy.getWithdrawNum());//原有的数量
                                BigDecimal withdrawNum = originalNum.add(inputNum);//新的退料数量 = 原有数量 + 退料数量
                                //退料更新库存操作
                                /*QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("materiel_code", mCode);
                                MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);*/
                                MesStockManage stockManage =null;
                                if (StringUtils.isNotEmpty(mesCertificateItem.getStorageSite())&&"不良品仓".equals(mesCertificateItem.getStorageSite())){
                                    stockManage = mesStockManageService.queryByMcodeAndClientblp(mCode,mesOrderProduce.getClient());
                                }else{
                                    stockManage = mesStockManageService.queryByMcodeAndClient(mCode,mesOrderProduce.getClient());
                                }
                                System.out.println("退料："+mCode+"  客戶："+mesOrderProduce.getClient()+" stockManage:"+stockManage);
                                if (stockManage != null) {
                                    BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                    BigDecimal stockNewNum = stockNum.add(inputNum);//新库存数量 = 库存数量 + 退料数量
                                    stockManage.setStockNum(stockNewNum.toString());
                                    mesStockManageService.updateById(stockManage);

                                    //更新领料表的退料数量
                                    mesMaterielOccupy.setWithdrawNum(withdrawNum.toString());
                                    mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                    //更新制令单Bom表的退料数量
                                    commandbillPitem.setWithdrawNum(withdrawNum.toString());
                                    produceClient.editComitem(commandbillPitem);
                                } else {
                                    return Result.error("没有找到库存数据！请检查！");
                                }

                            } else {
                                return Result.error("没有找到物料领用信息！请检查！");
                            }
                        } else {
                            return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                        }
                    }
                }
                //266 制令单转产
                if (certificateItem1.getMobileCode().equals("266")) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    String mCode = commandbillPitem.getMaterielCode();//物料料号
                    //通过转产制令单号和物料料号，通过远程调用，获取转产制令单Bom的数据
                    String changeCode = mesCertificateItem.getQuery5();//转产制令单号
                    MesCommandbillPitem pitem = produceClient.getPitemByCode(changeCode, mCode);
                    //转产记录表
                    TurnProduceRecord turnProduceRecord = new TurnProduceRecord();
                    //没有查询出来的进入退料操作
                    if (pitem != null) {
                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
                        BigDecimal consumeNum = new BigDecimal(commandbillPitem.getConsumeNum());//已消耗数量
                        BigDecimal withdrawNum = new BigDecimal(commandbillPitem.getWithdrawNum());//已退料料数量
                        BigDecimal unglazeNum = new BigDecimal(commandbillPitem.getUnglazeNum());//已上料数量
                        if (StringUtils.isBlank(commandbillPitem.getTransformNum())) {
                            commandbillPitem.setTransformNum("0");
                        }
                        BigDecimal transformNum = new BigDecimal(commandbillPitem.getTransformNum());//已转产数量
                        BigDecimal shiyongNum = consumeNum.add(withdrawNum).add(transformNum);//已使用数量=已消耗数量+已退料料数量+已转产数量
                        BigDecimal adviceNum = deliveryNum.subtract(consumeNum.add(withdrawNum).add(transformNum));//建议转产数量
                        BigDecimal realNum = new BigDecimal(mesCertificateItem.getInputNum());//实际转产数量

                        //根据原制令单上料剩余的数量，复制一份上料数据,转产上料数量
                        String wareNum = mesStorageWholesaleService.updateCommandbill(commandbillPitem.getCommandbillId(), shiyongNum.toString(), mCode, pitem.getId(), pitem.getCommandbillId());
                        if (StringUtils.isBlank(pitem.getUnglazeNum())) {
                            pitem.setUnglazeNum("0");
                        }
                        if (StringUtils.isBlank(wareNum)) {
                            wareNum = "0";
                        }
                        if (realNum.compareTo(adviceNum) == 1) {
                            return Result.error("数量不符！请检查！");
                        } else {
                            //进入转产操作
                            if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(pitem.getProorderId()) && StringUtils.isNotBlank(mCode)) {
                                //通过订单id与物料料号，查询领料表信息
                                String orderId = pitem.getProorderId();//转产制令单管理的生产订单id
                                String produceId = commandbillPitem.getProorderId();//原有制令单关联的生产订单id
                                if (!produceId.equals(orderId)) {
                                    QueryWrapper<MesMaterielOccupy> occupyWrapper = new QueryWrapper<>();
                                    occupyWrapper.eq("order_id", produceId).eq("materiel_code", mCode);
                                    MesMaterielOccupy materielOccupy = mesMaterielOccupyService.getOne(occupyWrapper);
                                    //领料记录是空的则新增领料记录
                                    if (materielOccupy == null) {
                                        materielOccupy = new MesMaterielOccupy();
                                        materielOccupy.setOrderId(orderId);
                                        MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                        if (mesOrderProduce != null) {
                                            materielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                            materielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                        }
                                        materielOccupy.setMaterielCode(mCode);
                                        materielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                        materielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                        if (commandbillPitem != null) {
                                            materielOccupy.setOccupyNum(commandbillPitem.getRequireNum());
                                        }
                                        materielOccupy.setUnusedNum("0");
                                        materielOccupy.setWithdrawNum("0");
                                        BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                        //更新领料表的转产数量
                                        materielOccupy.setTransformNum(transNewnum.toString());
                                        mesMaterielOccupyService.save(materielOccupy);
                                    }
                                    if (materielOccupy != null) {
                                        BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                        //更新领料表的转产数量
                                        materielOccupy.setTransformNum(transNewnum.toString());
                                        mesMaterielOccupyService.updateById(materielOccupy);
                                        //更新原有制令单Bom表的转产数量
                                        commandbillPitem.setTransformNum(transNewnum.toString());
                                        //更新发料数量=原已发料数量-转产数量
                                        /*BigDecimal deliveryNewNum = deliveryNum.subtract(transformNum);
                                        commandbillPitem.setDeliveryNum(deliveryNewNum.toString());*/
                                        //转产的上料数量=原已上料数量-转产上料数量
                                        /*BigDecimal wareNums = new BigDecimal(wareNum);
                                        BigDecimal unglazeNewNum = unglazeNum.subtract(wareNums);
                                        commandbillPitem.setUnglazeNum(unglazeNewNum.toString());*/
                                        produceClient.editComitem(commandbillPitem);
                                    }

                                    QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                    materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                                    MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                                    //领料记录是空的则新增领料记录
                                    if (mesMaterielOccupy == null) {
                                        mesMaterielOccupy = new MesMaterielOccupy();
                                        mesMaterielOccupy.setOrderId(orderId);
                                        MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                        if (mesOrderProduce != null) {
                                            mesMaterielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                            mesMaterielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                        }
                                        mesMaterielOccupy.setMaterielCode(mCode);
                                        mesMaterielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                        mesMaterielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                        if (pitem != null) {
                                            mesMaterielOccupy.setOccupyNum(pitem.getRequireNum());
                                        }
                                        mesMaterielOccupy.setUnusedNum("0");
                                        mesMaterielOccupy.setWithdrawNum("0");
                                        mesMaterielOccupy.setTransformNum("0");
                                        BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的数量
                                        BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有数量 + 转产数量
                                        //更新领料表的退料数量
                                        mesMaterielOccupy.setSendNum(deliveryNewnum.toString());
                                        mesMaterielOccupyService.save(mesMaterielOccupy);
                                    }

                                    if (mesMaterielOccupy != null) {
                                        BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的数量
                                        BigDecimal unglazeNum2 = new BigDecimal(pitem.getUnglazeNum());//原有的上料数量
                                        BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有数量 + 转产数量
                                        //更新领料表的退料数量
                                        mesMaterielOccupy.setSendNum(deliveryNewnum.toString());
                                        mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                        //更新转产制令单Bom表的发料数量
                                        pitem.setDeliveryNum(deliveryNewnum.toString());
                                        //转产上料数量
                                        BigDecimal wareNums = new BigDecimal(wareNum);
                                        BigDecimal unglazeNumadd = unglazeNum2.add(wareNums);
                                        pitem.setUnglazeNum(unglazeNumadd.toString());
                                        produceClient.editComitem(pitem);
                                    }
                                } else {
                                    BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                    commandbillPitem.setTransformNum(transNewnum.toString());
                                    //转产的上料数量=原已上料数量-转产上料数量
                                    BigDecimal wareNums = new BigDecimal(wareNum);
                                    /*BigDecimal unglazeNewNum = unglazeNum.subtract(wareNums);
                                    commandbillPitem.setUnglazeNum(unglazeNewNum.toString());*/
                                    produceClient.editComitem(commandbillPitem);

                                    BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的数量
                                    BigDecimal unglazeNum2 = new BigDecimal(pitem.getUnglazeNum());//原有的上料数量
                                    BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有数量 + 转产数量
                                    pitem.setDeliveryNum(deliveryNewnum.toString());
                                    //转产上料数量
                                    BigDecimal unglazeNumadd = unglazeNum2.add(wareNums);
                                    pitem.setUnglazeNum(unglazeNumadd.toString());
                                    produceClient.editComitem(pitem);
                                }
                            } else {
                                return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                            }
                            BigDecimal cetificateOldNum = new BigDecimal(certificateItem1.getInputNum());//原有数量
                            BigDecimal cetificateNum = cetificateOldNum.add(realNum);//转产数量
                            certificateItem1.setInputNum(cetificateNum.toString());//新的转产数量 = 原有数量+转产数量
                        }
                    } else {
                        return Result.error("没有找到转产制令单BOM的数据！请检查！");
                    }

                }
                // 201 制令单扫描入库
                if (certificateItem1.getMobileCode().equals("201")) {
                    return Result.ok(certificateItem1);
                }
                // 601 发货  603 扫描发货
                if (certificateItem1.getMobileCode().equals("601")) {
                    MesSaleItem mesSaleItem = transactionClient.queryMesSaleItemById(mesCertificateItem.getReserveCode());
                    BigDecimal oldNum = new BigDecimal(certificateItem1.getInputNum());//已有数量
                    BigDecimal undeliveryNum = new BigDecimal(mesSaleItem.getUndeliveryNum());//未发货数量
                    BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//发货数量
                    BigDecimal remainNum = undeliveryNum.subtract(inputNum);//剩余数量 = 未发货数量 - 发货数量
                    if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                        return Result.error("发货数量与未发货数量不符！请检查！");
                    } else {
                        BigDecimal inputNumNew = oldNum.add(inputNum);
                        if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                            mesSaleItem.setState("完成");//全部发货完成，改变销售订单状态为完成
                            String saleId = mesSaleItem.getSaleorderId();
                            MesOrderSale mesOrderSale = transactionClient.queryMesSaleOrderById(saleId);
                            if (mesOrderSale != null) {
                                mesOrderSale.setState("完成");
                                transactionClient.editSaleOrder(mesOrderSale);
                            }
                            certificateItem1.setInputNum(inputNumNew.toString());
                        }
                        certificateItem1.setInputNum(inputNumNew.toString());

                        QueryWrapper<MesStockManage> stockWrapper = new QueryWrapper<>();
                        stockWrapper.eq("materiel_code", mesSaleItem.getMaterielCode());
                        MesStockManage stockManage = mesStockManageService.getOne(stockWrapper);
                        if (stockManage != null) {
                            BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());//原有的库存数量
                            BigDecimal newStockNum = stockNum.subtract(inputNum);//新的库存数量 = 原有的库存数量 - 发货数量
                            if (newStockNum.compareTo(BigDecimal.ZERO) == -1) {
                                return Result.error("" + mesSaleItem.getMaterielName() + " 的库存数量不足！无法发货！");
                            } else {
                                stockManage.setStockNum(newStockNum + "");
                                mesStockManageService.updateById(stockManage);
                                mesSaleItem.setUndeliveryNum(remainNum.toString());
                                transactionClient.editSaleItem(mesSaleItem);
                                if (StringUtils.isNotBlank(stockManage.getMinimum())) {
                                    BigDecimal minimum = new BigDecimal(stockManage.getMinimum());//库存临界点
                                    //如果库存到达库存临界点，则提醒用户及时采购
                                    if (newStockNum.compareTo(minimum) < 1) {
                                        // 获取登录用户信息
                                        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                                        //测试时，向当前登录用户发送消息提醒；正式上线后，需要向采购人员（溢哲渝设定）发送库存临界点警告
                                        systemClient.sendMessage(sysUser.getUsername(), stockManage.getMaterielName());
                                        systemClient.sendMessage(mesSaleItem.getCreateBy(), stockManage.getMaterielName());
                                    }
                                }
                            }
                        } else {
                            return Result.error("找不到 " + mesSaleItem.getMaterielName() + " 的库存数据！请检查！");
                        }
                    }
                }
                // 602 退货
                if (certificateItem1.getMobileCode().equals("602")) {
                    MesSaleItem mesSaleItem = transactionClient.queryMesSaleItemById(mesCertificateItem.getReserveCode());
                    BigDecimal orderNum = new BigDecimal(mesSaleItem.getOrderNum());//订单数量
                    BigDecimal oldNum = new BigDecimal(certificateItem1.getInputNum());//已有数量
                    BigDecimal undeliveryNum = new BigDecimal(mesSaleItem.getUndeliveryNum());//未发货数量
                    BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//退货数量
                    BigDecimal newNum = undeliveryNum.add(inputNum);
                    BigDecimal remainNum = orderNum.subtract(inputNum);
                    if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                        return Result.error("数量不符！请检查！");
                    } else if (newNum.compareTo(orderNum) == 1) {
                        return Result.error("数量不符！请检查！");
                    } else {
                        BigDecimal newInputNum = oldNum.add(inputNum);
                        certificateItem1.setInputNum(newInputNum.toString());
                        mesSaleItem.setUndeliveryNum(newNum.toString());
                        transactionClient.editSaleItem(mesSaleItem);
                    }
                }
                // 603 扫描发货
                if (certificateItem1.getMobileCode().equals("603")) {
                    System.err.println("你的思路是对的！");
                    return Result.ok(certificateItem1);
                }
                mesCertificateItemService.updateById(certificateItem1);
                return Result.ok(certificateItem1);
            } else if (certificateItemList.size() > 1) {
                System.err.println("找到多条数据！进行批量修改");
                //267 制令单批量退料
                if (mesCertificateItem.getMobileCode().equals("267")) {
                    List<MesCommandbillPitem> mesCommandbillPitemList = mesCertificateItem.getMesCommandbillPitemList();
                    if (mesCommandbillPitemList.size() != 0) {
                        for (MesCommandbillPitem commandbillPitem : mesCommandbillPitemList) {
                            BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
                            BigDecimal consumeNum = new BigDecimal(commandbillPitem.getConsumeNum());//已消耗数量
                            BigDecimal withdrawNum = new BigDecimal(commandbillPitem.getWithdrawNum());//已退料数量
                            BigDecimal realNum = new BigDecimal(commandbillPitem.getVirtualNum());//实际退料数量
                            BigDecimal withdrawNewNum = withdrawNum.add(realNum);//新退料数量 = 已退料数量+实际退料数量
                            BigDecimal adviceNum = deliveryNum.subtract(consumeNum);//建议退料数量
                            commandbillPitem.setAdviceNum(adviceNum.toString());
                            if (realNum.compareTo(adviceNum) == 1 || withdrawNewNum.compareTo(adviceNum) == 1) {
                                return Result.error("数量不符！请检查！");
                            } else {
                                //退料操作
                                if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(commandbillPitem.getMaterielCode())) {
                                    //通过订单id与物料料号，查询领料表信息
                                    String orderId = commandbillPitem.getProorderId();//生产订单id
                                    String mCode = commandbillPitem.getMaterielCode();//物料料号
                                    //制令单退料时，将退料数量记录在物料领用表，并返回到库存上
                                    QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                    materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                                    MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                                    //领料记录是空的则新增领料记录
                                    if (mesMaterielOccupy == null) {
                                        mesMaterielOccupy = new MesMaterielOccupy();
                                        mesMaterielOccupy.setOrderId(orderId);
                                        MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                        if (mesOrderProduce != null) {
                                            mesMaterielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                            mesMaterielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                        }
                                        mesMaterielOccupy.setMaterielCode(mCode);
                                        mesMaterielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                        mesMaterielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                        if (commandbillPitem != null) {
                                            mesMaterielOccupy.setOccupyNum(commandbillPitem.getRequireNum());
                                        }
                                        mesMaterielOccupy.setUnusedNum("0");
                                        mesMaterielOccupy.setWithdrawNum("0");
                                        mesMaterielOccupy.setTransformNum("0");
                                        mesMaterielOccupyService.save(mesMaterielOccupy);
                                    }

                                    if (mesMaterielOccupy != null) {
                                        BigDecimal originalNum = new BigDecimal(commandbillPitem.getWithdrawNum());//原有的数量
                                        BigDecimal withdrawNewnum = originalNum.add(realNum);//新的退料数量 = 原有数量 + 退料数量
                                        //退料更新库存操作
                                        QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                                        queryWrapper.eq("materiel_code", mCode);
                                        MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                                        if (stockManage != null) {
                                            BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                            BigDecimal stockNewNum = stockNum.add(realNum);//新库存数量 = 库存数量 + 退料数量
                                            stockManage.setStockNum(stockNewNum.toString());
                                            mesStockManageService.updateById(stockManage);
                                            //更新领料表的退料数量
                                            mesMaterielOccupy.setWithdrawNum(withdrawNewnum.toString());
                                            mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                            //更新制令单Bom表的退料数量
                                            commandbillPitem.setWithdrawNum(withdrawNewnum.toString());//已退料数量
                                            commandbillPitem.setAdviceNum(adviceNum.toString());//建议退料数量
                                            produceClient.editComitem(commandbillPitem);
                                            //更新物料凭证数量
                                            QueryWrapper<MesCertificateItem> certificateWrapper = new QueryWrapper<>();
                                            certificateWrapper.eq("materiel_code", mCode).eq("perk_id", perkId).eq("mobile_code", "267");
                                            MesCertificateItem certificateItem = mesCertificateItemService.getOne(certificateWrapper);
                                            if (certificateItem != null) {
                                                BigDecimal certificateOldNum = new BigDecimal(certificateItem.getInputNum());
                                                BigDecimal certificateNum = certificateOldNum.add(realNum);
                                                certificateItem.setInputNum(certificateNum.toString());
                                                mesCertificateItemService.updateById(certificateItem);
                                            } else {
                                                return Result.error("没有找到物料凭证项目数据！请检查！");
                                            }
                                        } else {
                                            return Result.error("没有找到库存数据！请检查！");
                                        }
                                    } else {
                                        return Result.error("没有找到物料领用信息！请检查！");
                                    }
                                } else {
                                    return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                                }
                            }
                        }
                        return Result.ok("制令单批量退料成功");
                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查！");
                    }
                }
                //268 制令单批量转产
                if (mesCertificateItem.getMobileCode().equals("268")) {
                    List<MesCommandbillPitem> mesCommandbillPitemList = mesCertificateItem.getMesCommandbillPitemList();
                    if (mesCommandbillPitemList.size() != 0) {
                        String changeCode = mesCertificateItem.getQuery5();//转产制令单号
                        for (MesCommandbillPitem commandbillPitem : mesCommandbillPitemList) {
                            String mCode = commandbillPitem.getMaterielCode();//物料料号
                            //通过转产制令单号和物料料号，通过远程调用，获取转产制令单Bom的数据
                            MesCommandbillPitem pitem = produceClient.getPitemByCode(changeCode, mCode);
                            if (pitem != null) {
                                BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
//								BigDecimal glazeNum = new BigDecimal(commandbillPitem.getUnglazeNum());//已上料数量
                                BigDecimal consumeNum = new BigDecimal(commandbillPitem.getConsumeNum());//已消耗数量
                                BigDecimal withdrawNum = new BigDecimal(commandbillPitem.getWithdrawNum());//已退料料数量
                                if (StringUtils.isBlank(commandbillPitem.getTransformNum())) {
                                    commandbillPitem.setTransformNum("0");
                                }
                                BigDecimal transformNum = new BigDecimal(commandbillPitem.getTransformNum());//已转产数量
                                BigDecimal adviceNum = deliveryNum.subtract(consumeNum.add(withdrawNum).add(transformNum));//建议转产数量
                                BigDecimal realNum = new BigDecimal(commandbillPitem.getVirtualNum());//实际转产数量
                                if (realNum.compareTo(adviceNum) == 1) {
                                    return Result.error("数量不符！请检查！");
                                } else {
                                    //进入转产操作
                                    if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(pitem.getProorderId()) && StringUtils.isNotBlank(mCode)) {
                                        //通过订单id与物料料号，查询领料表信息
                                        String orderId = pitem.getProorderId();//转产制令单关联的生产订单id
                                        String produceId = commandbillPitem.getProorderId();//原有制令单关联的生产订单id
                                        if (!produceId.equals(orderId)) {
                                            QueryWrapper<MesMaterielOccupy> occupyWrapper = new QueryWrapper<>();
                                            occupyWrapper.eq("order_id", produceId).eq("materiel_code", mCode);
                                            MesMaterielOccupy materielOccupy = mesMaterielOccupyService.getOne(occupyWrapper);

                                            //领料记录是空的则新增领料记录
                                            if (materielOccupy == null) {
                                                materielOccupy = new MesMaterielOccupy();
                                                materielOccupy.setOrderId(orderId);
                                                MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                                if (mesOrderProduce != null) {
                                                    materielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                                    materielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                                }
                                                materielOccupy.setMaterielCode(mCode);
                                                materielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                                materielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                                if (commandbillPitem != null) {
                                                    materielOccupy.setOccupyNum(commandbillPitem.getRequireNum());
                                                }
                                                materielOccupy.setUnusedNum("0");
                                                materielOccupy.setWithdrawNum("0");
                                                materielOccupy.setTransformNum("0");
                                                mesMaterielOccupyService.save(materielOccupy);
                                            }

                                            if (materielOccupy != null) {
                                                BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                                //更新领料表的转产数量
                                                materielOccupy.setTransformNum(transNewnum.toString());
                                                mesMaterielOccupyService.updateById(materielOccupy);
                                                //更新原有制令单Bom表的转产数量
                                                commandbillPitem.setTransformNum(transNewnum.toString());
                                                produceClient.editComitem(commandbillPitem);
                                            } else {
                                                return Result.error("没有找到原有制令单的物料领用信息！请检查！");
                                            }
                                            //制令单退料时，将退料数量记录在物料领用表，并返回到库存上
                                            QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                            materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                                            MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);

                                            //领料记录是空的则新增领料记录
                                            if (mesMaterielOccupy == null) {
                                                mesMaterielOccupy = new MesMaterielOccupy();
                                                mesMaterielOccupy.setOrderId(orderId);
                                                MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                                if (mesOrderProduce != null) {
                                                    mesMaterielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                                    mesMaterielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                                }
                                                mesMaterielOccupy.setMaterielCode(mCode);
                                                mesMaterielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                                mesMaterielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                                if (pitem != null) {
                                                    mesMaterielOccupy.setOccupyNum(pitem.getRequireNum());
                                                }
                                                mesMaterielOccupy.setUnusedNum("0");
                                                mesMaterielOccupy.setWithdrawNum("0");
                                                mesMaterielOccupy.setTransformNum("0");
                                                mesMaterielOccupyService.save(mesMaterielOccupy);
                                            }

                                            if (mesMaterielOccupy != null) {
                                                BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的数量
                                                BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有数量 + 转产数量
                                                //更新领料表的退料数量
                                                mesMaterielOccupy.setSendNum(deliveryNewnum.toString());
                                                mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                                //更新转产制令单Bom表的发料数量
                                                pitem.setDeliveryNum(deliveryNewnum.toString());
                                                produceClient.editComitem(pitem);
                                            } else {
                                                return Result.error("没有找到转产制令单的物料领用信息！请检查！");
                                            }
                                        } else {
                                            BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                            commandbillPitem.setTransformNum(transNewnum.toString());
                                            produceClient.editComitem(commandbillPitem);

                                            BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的数量
                                            BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有数量 + 转产数量
                                            pitem.setDeliveryNum(deliveryNewnum.toString());
                                            produceClient.editComitem(pitem);
                                        }

                                        //更新物料凭证数量
                                        QueryWrapper<MesCertificateItem> certificateWrapper = new QueryWrapper<>();
                                        certificateWrapper.eq("materiel_code", mCode).eq("perk_id", perkId).eq("mobile_code", "268");
                                        MesCertificateItem certificateItem = mesCertificateItemService.getOne(certificateWrapper);
                                        if (certificateItem != null) {
                                            BigDecimal certificateOldNum = new BigDecimal(certificateItem.getInputNum());
                                            BigDecimal certificateNum = certificateOldNum.add(realNum);
                                            certificateItem.setInputNum(certificateNum.toString());
                                            mesCertificateItemService.updateById(certificateItem);
                                        } else {
                                            return Result.error("没有找到物料凭证项目数据！请检查！");
                                        }

                                    } else {
                                        return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                                    }
                                }
                            } else {
                                return Result.error("没有找到转产制令单BOM的数据！请检查！");
                            }
                        }
                        return Result.ok("制令单批量转产成功！");
                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查！");
                    }
                }

            } else if (certificateItemList.size() == 0) {
                System.err.println("找不到进行新增！");
                //103 物料入库/收货
                if (mesCertificateItem.getMobileCode().equals("103")) {
                    MesCertificatePerk mesCertificatePerk = mesCertificatePerkService.getById(perkId);
                    mesCertificatePerk.setIfFinish("未完成");
                    mesCertificatePerk.setIfInput("未完成");
                    mesCertificatePerkService.updateById(mesCertificatePerk);
                    //通过预留编号（采购订单子表ID），获取采购订单子表的相应数据
                    MesPurchaseItem purchaseItem = transactionClient.queryMesPurchaseItemById(mesCertificateItem.getReserveCode());
                    //获取未收货数量，与收货数量做对比判断
                    BigDecimal unreceiveNum = new BigDecimal(purchaseItem.getUnreceiveNum());//未收货数量
                    if (StringUtils.isNotBlank(mesCertificateItem.getInputNum())) {
                        BigDecimal receiveNum = new BigDecimal(mesCertificateItem.getInputNum());//收货数量
                        BigDecimal remainNum = unreceiveNum.subtract(receiveNum);// 剩余数量=未收货数量-收货数量
                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                            return Result.error("请检查收货数量是否正确！");
                        } else if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                            purchaseItem.setUnreceiveNum(remainNum.toString());
                            purchaseItem.setIfFinish("收货完成");
                            transactionClient.editPurchaseItem(purchaseItem);
                            //收货完成，向工作人员发送质检提醒；目前测试环境，向当前登录用户发送消息提醒，上线后修改
//                            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//                            systemClient.sendCheckMessage(sysUser.getUsername(), purchaseItem.getMaterielName(), mesCertificateItem.getInputNum(), purchaseItem.getOrderUnit());
                            asyncUtils.asyncSend(purchaseItem);
                        } else {
                            purchaseItem.setUnreceiveNum(remainNum.toString());
                            transactionClient.editPurchaseItem(purchaseItem);
                        }
                    }
                    mesCertificateItem.setIfInspect("否");
                    mesCertificateItem.setIfStorage("否");
                    String inputNum = mesCertificateItem.getInputNum();//数量
                    String unit = purchaseItem.getOrderUnit();//单位
                    String mName = purchaseItem.getMaterielName();//物料名称
                    mesCertificateItem.setUnstorageNum(inputNum);// 未入库数量 = 录入数量
                    mesCertificateItem.setMaterielId(purchaseItem.getMaterielId());// 物料id
                    mesCertificateItem.setMaterielCode(purchaseItem.getMaterielCode());// 物料编号
                    mesCertificateItem.setMaterielName(mName);// 物料名称
                    mesCertificateItem.setMaterielGauge(purchaseItem.getMaterielGauge());// 物料规格
                    mesCertificateItem.setInputUnit(unit);// 单位
                    mesCertificateItem.setFactoryId(purchaseItem.getFactoryId());//工厂id
                    mesCertificateItem.setFactoryCode(purchaseItem.getFactoryCode());// 工厂编号
                    mesCertificateItem.setFactoryName(purchaseItem.getFactoryName());// 工厂名称
                    mesCertificateItem.setStorageSite(purchaseItem.getStorageSite());// 库存地点
                }
                // 262 制令单入库
                if (mesCertificateItem.getMobileCode().equals("262")) {
                    // 通过预留编号（生产订单ID），获取生产订单的相应数据
                    MesOrderProduce mesOrderProduce = transactionClient.queryMesProduceById(mesCertificateItem.getReserveCode());
                    BigDecimal receiveNum = new BigDecimal(mesCertificateItem.getInputNum());
                    if (StringUtils.isNotBlank(mesCertificateItem.getCommandId())) {
                        MesCommandbillInfo mesCommandbillInfo = produceClient.getById(mesCertificateItem.getCommandId());
                        BigDecimal uninputNum = new BigDecimal(mesCommandbillInfo.getUninputNum());
                        BigDecimal remainNum = uninputNum.subtract(receiveNum);
                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                            return Result.error("请检查入库数量是否正确！");
                        } else if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                            mesCommandbillInfo.setUninputNum(remainNum.toString());
//							mesCommandbillInfo.setInputState("入库完成");
                            produceClient.editCommand(mesCommandbillInfo);
                        } else {
                            mesCommandbillInfo.setUninputNum(remainNum.toString());
                            produceClient.editCommand(mesCommandbillInfo);
                        }
                    }
                    mesCertificateItem.setIfInspect("否");
//			mesCertificateItem.setMaterielId(mesOrderProduce.getMaterielId());// 物料id
                    mesCertificateItem.setMaterielCode(mesOrderProduce.getMaterielCode()); //物料编号
                    mesCertificateItem.setMaterielName(mesOrderProduce.getMaterielName()); //物料名称
                    mesCertificateItem.setMaterielGauge(mesOrderProduce.getGauge());//物料规格
                    mesCertificateItem.setInputUnit(mesOrderProduce.getUnit());// 单位
                    mesCertificateItem.setFactoryId(mesOrderProduce.getFactoryId());//工厂id
                    mesCertificateItem.setFactoryCode(mesOrderProduce.getFactoryCode());//工厂编号
                    mesCertificateItem.setFactoryName(mesOrderProduce.getFactoryName()); //工厂名称
                    mesCertificateItem.setStorageSite(mesOrderProduce.getStorageSite());//库存地点(存储位置)

                    QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("materiel_code", mesOrderProduce.getMaterielCode());
                    MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                    if (stockManage != null) {
                        BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                        BigDecimal newStock = stockNum.add(receiveNum);
                        stockManage.setStockNum(newStock.toString());
                        mesStockManageService.updateById(stockManage);
                    } else {
                        MesStockManage mesStockManage = new MesStockManage();
                        mesStockManage.setMaterielCode(mesOrderProduce.getMaterielCode());
                        mesStockManage.setMaterielName(mesOrderProduce.getMaterielName());
                        mesStockManage.setMaterielGague(mesOrderProduce.getGauge());
                        mesStockManage.setFactoryId(mesOrderProduce.getFactoryId());
                        mesStockManage.setFactoryCode(mesOrderProduce.getFactoryCode());
                        mesStockManage.setFactoryName(mesOrderProduce.getFactoryName());
                        mesStockManage.setStoreName(mesOrderProduce.getStorageSite());
                        mesStockManage.setUnit(mesOrderProduce.getUnit());
                        mesStockManage.setStockNum(receiveNum + "");
                        MesChiefdataMateriel mater = systemClient.queryByMcode(mesStockManage.getMaterielCode());
                        if (mater != null) {
                            mesStockManage.setQuery5(mater.getMaterielType());
                        }
                        mesStockManageService.save(mesStockManage);
                    }

                }
                //261 制令单发料
                if (mesCertificateItem.getMobileCode().equals("261")) {
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                    if (StringUtils.isNotBlank(mesCertificateItem.getInputNum())) {
                        String orderId = commandbillPitem.getProorderId();//生产订单id
                        String mCode = commandbillPitem.getMaterielCode();//物料料号
                        String inputNum = mesCertificateItem.getInputNum();//发料数量
                        //制令单发料可以超发，先扣除领料单领取的数量；若超过领料数量，再从库存里扣除
                        QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                        materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                        MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                        if (mesMaterielOccupy != null) {
//							BigDecimal occupyNum = new BigDecimal(mesMaterielOccupy.getOccupyNum());//领用数量
                            BigDecimal unUsedNum = new BigDecimal(mesMaterielOccupy.getUnusedNum());//未使用数量
                            BigDecimal requireNum = new BigDecimal(inputNum);//发料数量
                            if (unUsedNum.compareTo(requireNum) == -1) {//物料超发
                                System.err.println("你的思路是对的！");
                                BigDecimal usedStockNum = requireNum.subtract(unUsedNum);//超发的数量
                                QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("materiel_code", mCode);
                                MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                                if (stockManage == null) {
                                    return Result.error("查不到库存数据！请检查！");
                                } else {
                                    BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());//库存数量
                                    BigDecimal minimum = new BigDecimal(stockManage.getMinimum());//库存临界点
                                    BigDecimal remainNum = stockNum.subtract(usedStockNum);//剩余数量=库存数量-超发数量
                                    //如果库存数量小于0，则提示库存数量不足。反之，将剩余数量，更新到库存上
                                    if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                                        return Result.error("库存数量不足！请检查！");
                                    } else {
                                        stockManage.setStockNum(remainNum + "");//新的库存数量 = 剩余数量
                                        mesStockManageService.updateById(stockManage);
                                        //如果库存数量小于库存临界点，则给用户发送消息提醒
                                        if (remainNum.compareTo(minimum) < 1) {
                                            // 获取登录用户信息
                                            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                                            //测试时，向当前登录用户发送消息提醒；正式上线后，需要向采购人员（溢哲渝设定）发送库存临界点警告
                                            systemClient.sendMessage(sysUser.getUsername(), stockManage.getMaterielName());
                                        }
                                        BigDecimal num = deliveryNum.add(requireNum);//新的发料数量 = 原有数量+发料数量
                                        commandbillPitem.setDeliveryNum(num.toString());
                                        produceClient.editComitem(commandbillPitem);
                                        //更新领料表数据
                                        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                                        mesMaterielOccupy.setOccupyPerson(sysUser.getUsername());//发料人
                                        mesMaterielOccupy.setSendNum(num.toString());//发料数量
                                        mesMaterielOccupy.setOccupyTime(new Date());//发料时间
                                        mesMaterielOccupy.setUnusedNum("0");
                                        mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                    }
                                }
                            } else {//未超发
                                BigDecimal remainNum = unUsedNum.subtract(requireNum);//剩余数量 = 未领用数量-发料数量
                                BigDecimal num = deliveryNum.add(requireNum);//新的发料数量 = 原有数量+发料数量
                                commandbillPitem.setDeliveryNum(num.toString());
                                produceClient.editComitem(commandbillPitem);
                                //更新领料表数据
                                LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                                mesMaterielOccupy.setOccupyPerson(sysUser.getUsername());//发料人
                                mesMaterielOccupy.setSendNum(num.toString());//发料数量
                                mesMaterielOccupy.setOccupyTime(new Date());//发料时间
                                mesMaterielOccupy.setUnusedNum(remainNum.toString());//未使用数量
                                mesMaterielOccupyService.updateById(mesMaterielOccupy);
                            }
                        } else {
                            return Result.error("领料数据为空！请检查！");
                        }
                    }
                    mesCertificateItem.setMaterielCode(commandbillPitem.getMaterielCode()); //物料编号
                    mesCertificateItem.setMaterielName(commandbillPitem.getMaterielName()); //物料名称
                    mesCertificateItem.setMaterielGauge(commandbillPitem.getMaterielGauge());//物料规格
                    mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                    mesCertificateItem.setFactoryCode(commandbillPitem.getFactoryCode());//工厂编号
                    mesCertificateItem.setFactoryName(commandbillPitem.getFactoryName()); //工厂名称
                    mesCertificateItem.setStorageSite(commandbillPitem.getStorageSite());//库存地点(存储位置)
                }
                //263 制令单上料
                if (mesCertificateItem.getMobileCode().equals("263")) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    BigDecimal glazeNum = new BigDecimal(commandbillPitem.getUnglazeNum()); //原有数量
                    BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                    BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//上料数量
                    BigDecimal glazeNewNum = glazeNum.add(inputNum);//已上料数量=原有数量+上料数量
                    //如果已上料数量超过已发料数量，则提示错误数量不符
                    if (glazeNewNum.compareTo(deliveryNum) == 1) {
                        return Result.error("数量不符！请先检查！");
                    } else {
                        commandbillPitem.setUnglazeNum(glazeNewNum.toString());
                        produceClient.editComitem(commandbillPitem);
                    }
                    mesCertificateItem.setMaterielCode(commandbillPitem.getMaterielCode()); //物料编号
                    mesCertificateItem.setMaterielName(commandbillPitem.getMaterielName()); //物料名称
                    mesCertificateItem.setMaterielGauge(commandbillPitem.getMaterielGauge());//物料规格
                    mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                    mesCertificateItem.setFactoryCode(commandbillPitem.getFactoryCode());//工厂编号
                    mesCertificateItem.setFactoryName(commandbillPitem.getFactoryName()); //工厂名称
                    mesCertificateItem.setStorageSite(commandbillPitem.getStorageSite());//库存地点(存储位置)
                }
                //264 制令单扫描发料
                if (mesCertificateItem.getMobileCode().equals("264")) {
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    mesCertificateItem.setMaterielCode(commandbillPitem.getMaterielCode()); //物料编号
                    mesCertificateItem.setMaterielName(commandbillPitem.getMaterielName()); //物料名称
                    mesCertificateItem.setMaterielGauge(commandbillPitem.getMaterielGauge());//物料规格
                    mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                    mesCertificateItem.setFactoryCode(commandbillPitem.getFactoryCode());//工厂编号
                    mesCertificateItem.setFactoryName(commandbillPitem.getFactoryName()); //工厂名称
                    mesCertificateItem.setStorageSite(commandbillPitem.getStorageSite());//库存地点(存储位置)
                }
                //265 制令单退料
                if (mesCertificateItem.getMobileCode().equals("265")) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                    BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum()); //退料数量
                    BigDecimal remainNum = deliveryNum.subtract(inputNum); //剩余数量 = 已发料数量 - 退料数量
                    if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                        return Result.error("数量不符!请检查！");
                    } else {
                        mesCertificateItem.setInputNum(inputNum.toString());
                        //退料操作
                        if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(commandbillPitem.getMaterielCode())) {
                            //通过订单id与物料料号，查询领料表信息
                            String orderId = commandbillPitem.getProorderId();//生产订单id
                            MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                            String mCode = commandbillPitem.getMaterielCode();//物料料号
                            //制令单退料时，将退料数量记录在物料领用表，并返回到库存上
                            QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                            materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                            MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                            if (mesMaterielOccupy != null) {
                                BigDecimal originalNum = new BigDecimal(mesMaterielOccupy.getWithdrawNum());//原有的数量
                                BigDecimal withdrawNum = originalNum.add(inputNum);//新的退料数量 = 原有数量 + 退料数量
                                //退料更新库存操作
                                /*QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("materiel_code", mCode);
                                MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);*/
                                MesStockManage stockManage =null;
                                if (StringUtils.isNotEmpty(mesCertificateItem.getStorageSite())&&"不良品仓".equals(mesCertificateItem.getStorageSite())){
                                    stockManage = mesStockManageService.queryByMcodeAndClientblp(mCode,mesOrderProduce.getClient());
                                }else {
                                    stockManage = mesStockManageService.queryByMcodeAndClient(mCode, mesOrderProduce.getClient());
                                }
                                System.out.println("退料==END："+mCode+"  客戶："+mesOrderProduce.getClient()+" stockManage:"+stockManage);
                                if (stockManage != null) {
                                    BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                    BigDecimal stockNewNum = stockNum.add(inputNum);//新库存数量 = 库存数量 + 退料数量
                                    stockManage.setStockNum(stockNewNum.toString());
                                    mesStockManageService.updateById(stockManage);
                                    //更新领料表的退料数量
                                    mesMaterielOccupy.setWithdrawNum(withdrawNum.toString());
                                    mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                    //更新制令单Bom表的退料数量
                                    commandbillPitem.setWithdrawNum(withdrawNum.toString());
                                    produceClient.editComitem(commandbillPitem);
                                } else {
                                    return Result.error("没有找到库存数据！请检查！");
                                }

                            } else {
                                return Result.error("没有找到物料领用信息！请检查！");
                            }
                        } else {
                            return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                        }
                    }
                    mesCertificateItem.setMaterielCode(commandbillPitem.getMaterielCode()); //物料编号
                    mesCertificateItem.setMaterielName(commandbillPitem.getMaterielName()); //物料名称
                    mesCertificateItem.setMaterielGauge(commandbillPitem.getMaterielGauge());//物料规格
                    mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                    mesCertificateItem.setFactoryCode(commandbillPitem.getFactoryCode());//工厂编号
                    mesCertificateItem.setFactoryName(commandbillPitem.getFactoryName()); //工厂名称
                    mesCertificateItem.setStorageSite(commandbillPitem.getStorageSite());//库存地点(存储位置)
                }
                //266 制令单转产
                if (mesCertificateItem.getMobileCode().equals("266")) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    //通过预留编号，获取制令单BOM表的相应数据
                    MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesCertificateItem.getReserveCode());
                    String mCode = commandbillPitem.getMaterielCode();//物料料号
                    //通过转产制令单号和物料料号，通过远程调用，获取转产制令单Bom的数据
                    String changeCode = mesCertificateItem.getQuery5();//转产制令单号
                    MesCommandbillPitem pitem = produceClient.getPitemByCode(changeCode, mCode);
                    if (pitem != null) {
                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
                        BigDecimal consumeNum = new BigDecimal(commandbillPitem.getConsumeNum());//已消耗数量
                        BigDecimal withdrawNum = new BigDecimal(commandbillPitem.getWithdrawNum());//已退料数量
                        if (StringUtils.isBlank(commandbillPitem.getTransformNum())) {
                            commandbillPitem.setTransformNum("0");
                        }
                        BigDecimal transformNum = new BigDecimal(commandbillPitem.getTransformNum());//已转产数量
                        BigDecimal adviceNum = deliveryNum.subtract(consumeNum.add(withdrawNum).add(transformNum));//建议转产数量
                        BigDecimal realNum = new BigDecimal(mesCertificateItem.getInputNum());//实际转产数量
                        if (realNum.compareTo(adviceNum) == 1) {
                            return Result.error("数量不符！请检查！");
                        } else {
                            //进入转产操作
                            if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(pitem.getProorderId()) && StringUtils.isNotBlank(mCode)) {
                                //通过订单id与物料料号，查询领料表信息
                                String orderId = pitem.getProorderId();//转产制令单关联的生产订单id
                                String produceId = commandbillPitem.getProorderId();//原有制令单关联的生产订单id
                                if (!produceId.equals(orderId)) {
                                    QueryWrapper<MesMaterielOccupy> occupyWrapper = new QueryWrapper<>();
                                    occupyWrapper.eq("order_id", produceId).eq("materiel_code", mCode);
                                    MesMaterielOccupy materielOccupy = mesMaterielOccupyService.getOne(occupyWrapper);
                                    //领料记录是空的则新增领料记录
                                    if (materielOccupy == null) {
                                        materielOccupy = new MesMaterielOccupy();
                                        materielOccupy.setOrderId(orderId);
                                        MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                        if (mesOrderProduce != null) {
                                            materielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                            materielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                        }
                                        materielOccupy.setMaterielCode(mCode);
                                        materielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                        materielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                        if (commandbillPitem != null) {
                                            materielOccupy.setOccupyNum(commandbillPitem.getRequireNum());
                                        }
                                        materielOccupy.setUnusedNum("0");
                                        materielOccupy.setWithdrawNum("0");
                                        materielOccupy.setTransformNum("0");
                                        mesMaterielOccupyService.save(materielOccupy);
                                    }
                                    if (materielOccupy != null) {
                                        BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                        //更新领料表的转产数量
                                        materielOccupy.setTransformNum(transNewnum.toString());
                                        mesMaterielOccupyService.updateById(materielOccupy);
                                        //更新原有制令单Bom表的转产数量
                                        commandbillPitem.setTransformNum(transNewnum.toString());
                                        produceClient.editComitem(commandbillPitem);
                                    } else {
                                        return Result.error("没有找到原有制令单的物料领用信息！请检查！");
                                    }

                                    //制令单转产时，将原有制令单的转产数量，加到转产制令单的物料领用单的发料数量上
                                    QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                    materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                                    MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);

                                    //领料记录是空的则新增领料记录
                                    if (mesMaterielOccupy == null) {
                                        mesMaterielOccupy = new MesMaterielOccupy();
                                        mesMaterielOccupy.setOrderId(orderId);
                                        MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                        if (mesOrderProduce != null) {
                                            mesMaterielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                            mesMaterielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                        }
                                        mesMaterielOccupy.setMaterielCode(mCode);
                                        mesMaterielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                        mesMaterielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                        if (pitem != null) {
                                            mesMaterielOccupy.setOccupyNum(pitem.getRequireNum());
                                        }
                                        mesMaterielOccupy.setUnusedNum("0");
                                        mesMaterielOccupy.setWithdrawNum("0");
                                        mesMaterielOccupy.setTransformNum("0");
                                        mesMaterielOccupyService.save(mesMaterielOccupy);
                                    }
                                    if (mesMaterielOccupy != null) {
                                        BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的发料数量
                                        BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有的发料数量 + 转产数量
                                        //更新领料表的发料数量
                                        mesMaterielOccupy.setSendNum(deliveryNewnum.toString());
                                        mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                        //更新转产制令单Bom表的发料数量
                                        pitem.setDeliveryNum(deliveryNewnum.toString());
                                        produceClient.editComitem(pitem);
                                    } else {
                                        return Result.error("没有找到转产制令单的物料领用信息！请检查！");
                                    }
                                } else {
                                    BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                    commandbillPitem.setTransformNum(transNewnum.toString());
                                    produceClient.editComitem(commandbillPitem);

                                    BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的数量
                                    BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有数量 + 转产数量
                                    pitem.setDeliveryNum(deliveryNewnum.toString());
                                    produceClient.editComitem(pitem);
                                }
                            } else {
                                return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                            }
                            mesCertificateItem.setId(null);
                            mesCertificateItem.setInputNum(realNum.toString());//退料数量
                            mesCertificateItem.setMaterielCode(commandbillPitem.getMaterielCode()); //物料编号
                            mesCertificateItem.setMaterielName(commandbillPitem.getMaterielName()); //物料名称
                            mesCertificateItem.setMaterielGauge(commandbillPitem.getMaterielGauge());//物料规格
                            mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                            mesCertificateItem.setFactoryCode("转产");//类型
                            mesCertificateItem.setFactoryName("原单号: " + commandbillPitem.getCommandbillCode()); //原制令单
                            mesCertificateItem.setStorageSite("转产单号: " + pitem.getCommandbillCode());//转产制令单号
                            mesCertificateItemService.save(mesCertificateItem);
                            return Result.ok("转产成功");
                        }
                    } else {
                        return Result.error("没有找到转产制令单BOM的数据！请检查！");
                    }

                }
                //267 制令单批量退料
                if (mesCertificateItem.getMobileCode().equals("267")) {
                    List<MesCommandbillPitem> mesCommandbillPitemList = mesCertificateItem.getMesCommandbillPitemList();
                    if (mesCommandbillPitemList.size() != 0) {
                        for (MesCommandbillPitem commandbillPitem : mesCommandbillPitemList) {
                            BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
                            BigDecimal consumeNum = new BigDecimal(commandbillPitem.getConsumeNum());//已消耗数量
                            BigDecimal withdrawNum = new BigDecimal(commandbillPitem.getWithdrawNum());//已退料数量
                            BigDecimal realNum = new BigDecimal(commandbillPitem.getVirtualNum());//实际退料数量
                            BigDecimal withdrawNewNum = withdrawNum.add(realNum);//新退料数量 = 已退料数量+实际退料数量
                            BigDecimal adviceNum = deliveryNum.subtract(consumeNum);//建议退料数量
                            commandbillPitem.setAdviceNum(adviceNum.toString());
                            if (realNum.compareTo(adviceNum) == 1 || withdrawNewNum.compareTo(adviceNum) == 1) {
                                return Result.error("数量不符！请检查！");
                            } else {
                                //退料操作
                                if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(commandbillPitem.getMaterielCode())) {
                                    //通过订单id与物料料号，查询领料表信息
                                    String orderId = commandbillPitem.getProorderId();//生产订单id
                                    String mCode = commandbillPitem.getMaterielCode();//物料料号
                                    //制令单退料时，将退料数量记录在物料领用表，并返回到库存上
                                    QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                    materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                                    MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                                    if (mesMaterielOccupy != null) {
                                        BigDecimal originalNum = new BigDecimal(commandbillPitem.getWithdrawNum());//原有的数量
                                        BigDecimal withdrawNewnum = originalNum.add(realNum);//新的退料数量 = 原有数量 + 退料数量
                                        //退料更新库存操作
                                        QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                                        queryWrapper.eq("materiel_code", mCode);
                                        MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                                        if (stockManage != null) {
                                            BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                            BigDecimal stockNewNum = stockNum.add(realNum);//新库存数量 = 库存数量 + 退料数量
                                            stockManage.setStockNum(stockNewNum.toString());
                                            mesStockManageService.updateById(stockManage);
                                            //更新领料表的退料数量
                                            mesMaterielOccupy.setWithdrawNum(withdrawNewnum.toString());
                                            mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                            //更新制令单Bom表的退料数量
                                            commandbillPitem.setWithdrawNum(withdrawNewnum.toString());
                                            produceClient.editComitem(commandbillPitem);
                                        } else {
                                            return Result.error("没有找到库存数据！请检查！");
                                        }
                                    } else {
                                        return Result.error("没有找到物料领用信息！请检查！");
                                    }
                                } else {
                                    return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                                }
                                mesCertificateItem.setId(null);
                                mesCertificateItem.setInputNum(realNum.toString());//退料数量
                                mesCertificateItem.setMaterielCode(commandbillPitem.getMaterielCode()); //物料编号
                                mesCertificateItem.setMaterielName(commandbillPitem.getMaterielName()); //物料名称
                                mesCertificateItem.setMaterielGauge(commandbillPitem.getMaterielGauge());//物料规格
                                mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                                mesCertificateItem.setFactoryCode(commandbillPitem.getFactoryCode());//工厂编号
                                mesCertificateItem.setFactoryName(commandbillPitem.getFactoryName()); //工厂名称
                                mesCertificateItem.setStorageSite(commandbillPitem.getStorageSite());//库存地点(存储位置)
                                mesCertificateItemService.save(mesCertificateItem);
                            }
                        }
                        return Result.ok("制令单批量退料成功");
                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查！");
                    }
                }
                //268 制令单批量转产
                if (mesCertificateItem.getMobileCode().equals("268")) {
                    List<MesCommandbillPitem> mesCommandbillPitemList = mesCertificateItem.getMesCommandbillPitemList();
                    if (mesCommandbillPitemList.size() != 0) {
                        String changeCode = mesCertificateItem.getQuery5();//转产制令单号
                        for (MesCommandbillPitem commandbillPitem : mesCommandbillPitemList) {
                            String mCode = commandbillPitem.getMaterielCode();//物料料号
                            //通过转产制令单号和物料料号，通过远程调用，获取转产制令单Bom的数据
                            MesCommandbillPitem pitem = produceClient.getPitemByCode(changeCode, mCode);
                            if (pitem != null) {
                                BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
                                BigDecimal consumeNum = new BigDecimal(commandbillPitem.getConsumeNum());//已消耗数量
                                BigDecimal withdrawNum = new BigDecimal(commandbillPitem.getWithdrawNum());//已退料料数量
                                if (StringUtils.isBlank(commandbillPitem.getTransformNum())) {
                                    commandbillPitem.setTransformNum("0");
                                }
                                BigDecimal transformNum = new BigDecimal(commandbillPitem.getTransformNum());//已转产数量
                                BigDecimal adviceNum = deliveryNum.subtract(consumeNum.add(withdrawNum).add(transformNum));//建议转产数量
                                BigDecimal realNum = new BigDecimal(commandbillPitem.getVirtualNum());//实际转产数量
                                if (realNum.compareTo(adviceNum) == 1) {
                                    return Result.error("数量不符！请检查！");
                                } else {
                                    //进入转产操作
                                    if (StringUtils.isNotBlank(commandbillPitem.getProorderId()) && StringUtils.isNotBlank(pitem.getProorderId()) && StringUtils.isNotBlank(mCode)) {
                                        //通过订单id与物料料号，查询领料表信息
                                        String orderId = pitem.getProorderId();//转产制令单关联的生产订单id
                                        String produceId = commandbillPitem.getProorderId();//原有制令单关联的生产订单id
                                        if (!produceId.equals(orderId)) {
                                            QueryWrapper<MesMaterielOccupy> occupyWrapper = new QueryWrapper<>();
                                            occupyWrapper.eq("order_id", produceId).eq("materiel_code", mCode);
                                            MesMaterielOccupy materielOccupy = mesMaterielOccupyService.getOne(occupyWrapper);
                                            if (materielOccupy != null) {
                                                BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                                //更新领料表的转产数量
                                                materielOccupy.setTransformNum(transNewnum.toString());
                                                mesMaterielOccupyService.updateById(materielOccupy);
                                                //更新原有制令单Bom表的转产数量
                                                commandbillPitem.setTransformNum(transformNum.toString());
                                                produceClient.editComitem(commandbillPitem);
                                            } else {
                                                return Result.error("没有找到原有制令单的物料领用信息！请检查！");
                                            }

                                            //制令单退料时，将退料数量记录在物料领用表，并返回到库存上
                                            QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                            materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                                            MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                                            if (mesMaterielOccupy != null) {
                                                BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的数量
                                                BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有数量 + 转产数量
                                                //更新领料表的发料数量
                                                mesMaterielOccupy.setSendNum(deliveryNewnum.toString());
                                                mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                                //更新转产制令单Bom表的发料数量
                                                pitem.setDeliveryNum(deliveryNewnum.toString());
                                                produceClient.editComitem(pitem);
                                            } else {
                                                return Result.error("没有找到转产制令单的物料领用信息！请检查！");
                                            }
                                        } else {
                                            BigDecimal transNewnum = transformNum.add(realNum);//新的转产数量 = 已转产数量 + 转产数量
                                            commandbillPitem.setTransformNum(transNewnum.toString());
                                            produceClient.editComitem(commandbillPitem);

                                            BigDecimal originalNum = new BigDecimal(pitem.getDeliveryNum());//原有的数量
                                            BigDecimal deliveryNewnum = originalNum.add(realNum);//新的发料数量 = 原有数量 + 转产数量
                                            pitem.setDeliveryNum(deliveryNewnum.toString());
                                            produceClient.editComitem(pitem);

                                        }
                                    } else {
                                        return Result.error("制令单Bom表里没有查询到订单id和物料料号！请检查！");
                                    }
                                    mesCertificateItem.setId(null);
                                    mesCertificateItem.setInputNum(realNum.toString());//退料数量
                                    mesCertificateItem.setMaterielCode(commandbillPitem.getMaterielCode()); //物料编号
                                    mesCertificateItem.setMaterielName(commandbillPitem.getMaterielName()); //物料名称
                                    mesCertificateItem.setMaterielGauge(commandbillPitem.getMaterielGauge());//物料规格
                                    mesCertificateItem.setInputUnit(commandbillPitem.getCountUnit());// 单位
                                    mesCertificateItem.setFactoryCode("制令单转产");//类型
                                    mesCertificateItem.setFactoryName("原单号: " + commandbillPitem.getCommandbillCode()); //原制令单
                                    mesCertificateItem.setStorageSite("转产单号: " + pitem.getCommandbillCode());//转产制令单号
                                    mesCertificateItemService.save(mesCertificateItem);
                                }
                            } else {
                                return Result.error("没有找到转产制令单BOM的数据！请检查！");
                            }
                        }
                        return Result.ok("制令单批量转产成功！");
                    } else {
                        return Result.error("没有找到制令单BOM的数据！请检查！");
                    }
                }
                // 201 制令单扫描入库
                if (mesCertificateItem.getMobileCode().equals("201")) {
                    //通过预留编号（生产订单id），获取生产订单主表的相应数据
                    MesOrderProduce produce = transactionClient.queryMesProduceById(mesCertificateItem.getReserveCode());
                    mesCertificateItem.setMaterielCode(produce.getMaterielCode()); //物料编号
                    mesCertificateItem.setMaterielName(produce.getMaterielName()); //物料名称
                    mesCertificateItem.setMaterielGauge(produce.getGauge());//物料编号
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    mesCertificateItem.setInputUnit(produce.getUnit());// 单位
                    mesCertificateItem.setFactoryCode(produce.getFactoryCode());//工厂编号
                    mesCertificateItem.setFactoryName(produce.getFactoryName()); //工厂名称
                    mesCertificateItem.setStorageSite(produce.getStorageSite());//库存地点(存储位置)
                }
                // 202 辅料退库
                if (mesCertificateItem.getMobileCode().equals("202")) {
                    //通过预留编号（物料凭证项目ID），获取物料凭证项目的相应数据
                    MesCertificateItem certificateItem = mesCertificateItemService.getById(mesCertificateItem.getReserveCode());
                    mesCertificateItem.setMaterielCode(certificateItem.getMaterielCode()); //物料编号
                    mesCertificateItem.setMaterielName(certificateItem.getMaterielName()); //物料名称
                    mesCertificateItem.setInputUnit(certificateItem.getInputUnit());// 单位
                    mesCertificateItem.setFactoryName(certificateItem.getFactoryName()); //工厂名称
                    mesCertificateItem.setStorageSite(certificateItem.getStorageSite());//库存地点(存储位置)
                }
                // 601 发货
                if (mesCertificateItem.getMobileCode().equals("601")) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    MesSaleItem mesSaleItem = transactionClient.queryMesSaleItemById(mesCertificateItem.getReserveCode());
                    BigDecimal undeliveryNum = new BigDecimal(mesSaleItem.getUndeliveryNum());//未发货数量
                    BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//发货数量
                    BigDecimal remainNum = undeliveryNum.subtract(inputNum);//剩余数量 = 未发货数量 - 发货数量
                    if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                        return Result.error("数量不符！请检查！");
                    } else {
                        if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                            mesSaleItem.setState("完成");//全部发货完成，改变销售订单状态为完成
                            String saleId = mesSaleItem.getSaleorderId();
                            MesOrderSale mesOrderSale = transactionClient.queryMesSaleOrderById(saleId);
                            if (mesOrderSale != null) {
                                mesOrderSale.setState("完成");
                                transactionClient.editSaleOrder(mesOrderSale);
                            }
                        }
                        mesSaleItem.setUndeliveryNum(remainNum.toString());
                        transactionClient.editSaleItem(mesSaleItem);

                        QueryWrapper<MesStockManage> stockWrapper = new QueryWrapper<>();
                        stockWrapper.eq("materiel_code", mesSaleItem.getMaterielCode());
                        MesStockManage stockManage = mesStockManageService.getOne(stockWrapper);
                        if (stockManage != null) {
                            BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                            BigDecimal newStockNum = stockNum.subtract(inputNum);
                            if (newStockNum.compareTo(BigDecimal.ZERO) == -1) {
                                return Result.error("" + mesSaleItem.getMaterielName() + " 的库存数量不足！无法发货！");
                            } else {
                                stockManage.setStockNum(newStockNum.toString());
                                mesStockManageService.updateById(stockManage);
                                if (StringUtils.isNotBlank(stockManage.getMinimum())) {
                                    BigDecimal minimum = new BigDecimal(stockManage.getMinimum());
                                    if (newStockNum.compareTo(minimum) < 1) {
                                        // 获取登录用户信息
                                        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                                        //测试时，向当前登录用户发送消息提醒；正式上线后，需要向采购人员（溢哲渝设定）发送库存临界点警告
                                        systemClient.sendMessage(sysUser.getUsername(), stockManage.getMaterielName());
                                        systemClient.sendMessage(mesSaleItem.getCreateBy(), stockManage.getMaterielName());
                                    }
                                }
                            }
                        } else {
                            return Result.error("找不到 " + mesSaleItem.getMaterielName() + " 的库存数据！请检查！");
                        }
                    }
                    mesCertificateItem.setMobileType("发货");
                    mesCertificateItem.setMaterielCode(mesSaleItem.getMaterielCode());
                    mesCertificateItem.setMaterielName(mesSaleItem.getMaterielName());
                    mesCertificateItem.setMaterielGauge(mesSaleItem.getMaterielGauge());
                    mesCertificateItem.setInputUnit(mesSaleItem.getUnit());
                    mesCertificateItem.setFactoryCode(mesSaleItem.getFactoryCode());
                    mesCertificateItem.setFactoryName(mesSaleItem.getFactoryName());
                    mesCertificateItem.setStorageSite(mesSaleItem.getStorageSite());
                }
                // 602 退货
                if (mesCertificateItem.getMobileCode().equals("602")) {
                    MesSaleItem mesSaleItem = transactionClient.queryMesSaleItemById(mesCertificateItem.getReserveCode());
                    BigDecimal orderNum = new BigDecimal(mesSaleItem.getOrderNum());//订单数量
                    BigDecimal undeliveryNum = new BigDecimal(mesSaleItem.getUndeliveryNum());//未发货数量
                    BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//退货数量
                    BigDecimal newNum = undeliveryNum.add(inputNum);//新的未发货数量 = 未发货数量 + 退货数量
                    BigDecimal remainNum = orderNum.subtract(inputNum);//剩余数量 = 订单数量 - 退货数量
                    if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                        return Result.error("数量不符！请检查！");
                    } else if (newNum.compareTo(orderNum) == 1) {
                        return Result.error("数量不符！请检查！");
                    } else {
                        mesSaleItem.setUndeliveryNum(newNum + "");
                        transactionClient.editSaleItem(mesSaleItem);
                    }
                    mesCertificateItem.setMobileType("退货");
                    mesCertificateItem.setMaterielCode(mesSaleItem.getMaterielCode());
                    mesCertificateItem.setMaterielName(mesSaleItem.getMaterielName());
                    mesCertificateItem.setMaterielGauge(mesSaleItem.getMaterielGauge());
                    mesCertificateItem.setInputUnit(mesSaleItem.getUnit());
                    mesCertificateItem.setFactoryCode(mesSaleItem.getFactoryCode());
                    mesCertificateItem.setFactoryName(mesSaleItem.getFactoryName());
                    mesCertificateItem.setStorageSite(mesSaleItem.getStorageSite());
                }
                // 603 扫描发货
                if (mesCertificateItem.getMobileCode().equals("603")) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    MesSaleItem mesSaleItem = transactionClient.queryMesSaleItemById(mesCertificateItem.getReserveCode());
                    mesCertificateItem.setMobileType("扫描发货");
                    mesCertificateItem.setMaterielCode(mesSaleItem.getMaterielCode());
                    mesCertificateItem.setMaterielName(mesSaleItem.getMaterielName());
                    mesCertificateItem.setMaterielGauge(mesSaleItem.getMaterielGauge());
                    mesCertificateItem.setInputUnit(mesSaleItem.getUnit());
                    mesCertificateItem.setFactoryCode(mesSaleItem.getFactoryCode());
                    mesCertificateItem.setFactoryName(mesSaleItem.getFactoryName());
                    mesCertificateItem.setStorageSite(mesSaleItem.getStorageSite());
                }
                mesCertificateItemService.save(mesCertificateItem);
            }
        }
        return Result.ok(mesCertificateItem);
    }

    /**
     * 编辑
     *
     * @param mesCertificateItem
     * @return
     */
    @AutoLog(value = "物料凭证项目-编辑")
    @ApiOperation(value = "物料凭证项目-编辑", notes = "物料凭证项目-编辑")
    @PutMapping(value = "/editMesCertificateItem")
    public Result<?> editMesCertificateItem(@RequestBody MesCertificateItem mesCertificateItem) {
        mesCertificateItemService.updateById(mesCertificateItem);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "物料凭证项目-通过id删除")
    @ApiOperation(value = "物料凭证项目-通过id删除", notes = "物料凭证项目-通过id删除")
    @DeleteMapping(value = "/deleteMesCertificateItem")
    public Result<?> deleteMesCertificateItem(@RequestParam(name = "id", required = true) String id) {
//		MesCertificateItem mesCertificateItem = mesCertificateItemService.getById(id);
//		if(StringUtils.isNotBlank(mesCertificateItem.getCommandId()) && StringUtils.isNotBlank(mesCertificateItem.getMobileCode())){
//			String commandId = mesCertificateItem.getCommandId();
//			String mobileCode = mesCertificateItem.getMobileCode();
//			if(mobileCode.equals("262") || mobileCode.equals("201")){
//				MesCommandbillInfo commandbillInfo = produceClient.getById(commandId);
//				BigDecimal num = new BigDecimal(mesCertificateItem.getInputNum());
//				commandbillInfo.setUninputNum(num.toString());
//				commandbillInfo.setInputState("未完成");
//				produceClient.editCommand(commandbillInfo);
//			}
//		}
        mesCertificateItemService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "物料凭证项目-批量删除")
    @ApiOperation(value = "物料凭证项目-批量删除", notes = "物料凭证项目-批量删除")
    @DeleteMapping(value = "/deleteBatchMesCertificateItem")
    public Result<?> deleteBatchMesCertificateItem(@RequestParam(name = "ids", required = true) String ids) {
        this.mesCertificateItemService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportMesCertificateItem")
    public ModelAndView exportMesCertificateItem(HttpServletRequest request, MesCertificateItem mesCertificateItem) {
        // Step.1 组装查询条件
        QueryWrapper<MesCertificateItem> queryWrapper = QueryGenerator.initQueryWrapper(mesCertificateItem, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<MesCertificateItem> pageList = mesCertificateItemService.list(queryWrapper);
        List<MesCertificateItem> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "物料凭证项目"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, MesCertificateItem.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("物料凭证项目报表", "导出人:" + sysUser.getRealname(), "物料凭证项目"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importMesCertificateItem/{mainId}")
    public Result<?> importMesCertificateItem(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MesCertificateItem> list = ExcelImportUtil.importExcel(file.getInputStream(), MesCertificateItem.class, params);
                for (MesCertificateItem temp : list) {
                    temp.setPerkId(mainId);
                }
                long start = System.currentTimeMillis();
                mesCertificateItemService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }
    /*--------------------------------子表处理-物料凭证项目-end----------------------------------------------*/

    public void addOutWaterRecord(MesCertificateItem mesCertificateItem, String inputnum) {
//        //根据制令单id查询制令单信息
//        MesCommandbillInfo commandbillInfo = produceClient.getById(mesCertificateItem.getCommandId());
//
//        //根据生产订单id查询生产订单信息
//        MesOrderProduce orderProduce = (MesOrderProduce) transactionClient.queryById(commandbillInfo.getProduceId()).getResult();
//
//        MesOutproWater outproWater = new MesOutproWater();
//        //出货时间
//        outproWater.setOutproTime(new Date());
//        //出货数量
//        outproWater.setOutproNums(Integer.parseInt(mesCertificateItem.getInputNum()));
//        //客户名称
//        outproWater.setClientName(commandbillInfo.getClientName());
//        //订单数量
//        if(orderProduce!=null) {
//            outproWater.setOrderNums(Integer.parseInt(orderProduce.getGrossAccount()));
//            //产品名称
//            outproWater.setProductName(orderProduce.getOrderName());
//        }
//        //出货单号
//        outproWaterService.save(outproWater);

        MesStorageWholesale sale = new MesStorageWholesale();
        MesSaleItem item = transactionClient.queryMesSaleItemById(mesCertificateItem.getReserveCode());
        if (item != null) {
            sale.setBaseCode(item.getSaleorderId());
        }
        sale.setProductCode(mesCertificateItem.getMaterielCode());
        sale.setProductName(mesCertificateItem.getMaterielName());
        sale.setShelfCode(mesCertificateItem.getQuery5());
        sale.setShelfState(mesCertificateItem.getQuery6());
        sale.setBaseDockettype("扫描发货");
        sale.setInwareNum(inputnum);
        sale.setUnit(mesCertificateItem.getInputUnit());
        sale.setQuery1(DateUtils.getDate("yyyy/MM/dd HH:mm:ss"));
        mesStorageWholesaleService.save(sale);
    }

    /**
     * 参数设置
     */
    private void setParam(MaterielRetreatRecord materielRetreatRecord, MesCertificateItem oldCertificateItem, MesCertificateItem newCertificateItem) {
        materielRetreatRecord.setState("1");//质检后
        materielRetreatRecord.setClientCode(oldCertificateItem.getClientCode());//客户料号
        materielRetreatRecord.setMaterielName(oldCertificateItem.getMaterielName());//品名
        materielRetreatRecord.setMaterielCode(oldCertificateItem.getMaterielCode());//物料料号
        materielRetreatRecord.setMaterielSpecs(oldCertificateItem.getMaterielGauge());//规格
        materielRetreatRecord.setUnit(oldCertificateItem.getInputUnit());//单位
        materielRetreatRecord.setRetreatNum(newCertificateItem.getReturnNum());//退料数量
        materielRetreatRecord.setBirDay(new Date());//退料日期
        materielRetreatRecord.setRemarks("入库退料");
        materielRetreatRecord.setUretreatNum(this.calculateTheSum(oldCertificateItem.getUnstorageNum(), oldCertificateItem.getInputNum()));//实收数量
    }

    /**
     * 计算实收数量=未入库数量+录入数量
     */
    private static String calculateTheSum(String unStorageNum, String inputNum) {
        if (StringUtils.isEmpty(unStorageNum)) {
            unStorageNum = "0";
        }
        if (StringUtils.isEmpty(inputNum)) {
            inputNum = "0";
        }
        BigDecimal wNum = new BigDecimal(unStorageNum);
        BigDecimal yNum = new BigDecimal(inputNum);
        return wNum.add(yNum).toString();
    }

    /**
     * 录入数量=以录入数量-退料数量
     */
    private static String calculateTheDifference(String inputNum, String returnNum) {
        if (StringUtils.isEmpty(returnNum)) {
            returnNum = "0";
        }
        if (StringUtils.isEmpty(inputNum)) {
            inputNum = "0";
        }
        BigDecimal yNum = new BigDecimal(inputNum);
        BigDecimal tNum = new BigDecimal(returnNum);
        return yNum.subtract(tNum).toString();
    }

    /**
     * 记录错误操作
     */
    private void recordErrorOperation(String callAddress, String operationSteps, String wrongSteps, String errMeg, String commandBillId) {
        // 获取登录用户信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MesErrorOperationRecord errorOperationRecord = new MesErrorOperationRecord();
        errorOperationRecord.setCreateBy(sysUser.getRealname());//创建人
        //errorOperationRecord.setCreateTime(new Date);//创建日期
        errorOperationRecord.setSysOrgCode(sysUser.getOrgCode());//所属部门
        errorOperationRecord.setOperatorId(sysUser.getId());//操作人ID
        errorOperationRecord.setOperatorAccount(sysUser.getUsername());//操作人账号
        errorOperationRecord.setPhone(sysUser.getPhone());//操作人电话
        //errorOperationRecord.setUserStatus(sysUser.getStatus());//用户状态

        errorOperationRecord.setCallAddress(callAddress);//调用地址
        errorOperationRecord.setOperationSteps(operationSteps);//操作步骤
        errorOperationRecord.setWrongSteps(wrongSteps);//错误步骤
        errorOperationRecord.setErrorCause(errMeg);//错误原因
        if (StringUtils.isNotBlank(commandBillId)) {
            MesCommandbillInfo mesCommandBillInfo = produceClient.getById(commandBillId);
            if (com.epms.util.ObjectHelper.isNotEmpty(mesCommandBillInfo)) {
                errorOperationRecord.setLineType(mesCommandBillInfo.getLineType());//线别
                errorOperationRecord.setProduceGrade(mesCommandBillInfo.getProduceGrade());//阶别
            }
        }
        //errorOperationRecord.setRemark();//备注
        iMesErrorOperationRecordService.add(errorOperationRecord);
    }
}

